在 Python 3 中使用 BeautifulSoup 抓取 URL

TAN*_*-OK 2 python urllib beautifulsoup python-3.x

我尝试了这段代码,但包含 URL 的列表仍为空。没有错误按摩,什么都没有。

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

req = Request('https://www.metacritic.com/browse/movies/genre/date?page=0', headers={'User-Agent': 'Mozilla/5.0'})
html_page = urlopen(req).read()

soup = BeautifulSoup(html_page, features="xml")
links = []
for link in soup.findAll('a', attrs={'href': re.compile("^https://www.metacritic.com/movie/")}):
    links.append(link.get('href'))

print(links)
Run Code Online (Sandbox Code Playgroud)

我想抓取在给定 URL“ https://www.metacritic.com/browse/movies/genre/date ? ”中找到的所有以“ https://www.metacritic.com/movie/”开头的 URL?页=0 “。

我究竟做错了什么?

lei*_*opi 6

首先,您应该使用标准库“html.parser”而不是“xml”来解析页面内容。它可以更好地处理损坏的 html(请参阅Beautiful Soup findAll 没有找到全部

然后看一下你正在解析的页面的源代码。您要查找的元素如下所示:<a href="/movie/woman-at-war">

所以像这样改变你的代码:

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import re

req = Request('https://www.metacritic.com/browse/movies/genre/date?page=0', headers={'User-Agent': 'Mozilla/5.0'})
html_page = urlopen(req).read()

soup = BeautifulSoup(html_page, 'html.parser')
links = []
for link in soup.findAll('a', attrs={'href': re.compile("^/movie/")}):
    links.append(link.get('href'))

print(links)
Run Code Online (Sandbox Code Playgroud)