在 Python 中使用 BeautifulSoup 抓取 URL 3
Scrape URLs using BeautifulSoup in Python 3
我试过这段代码,但带有 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)
我想抓取所有以“https://www.metacritic.com/movie/" that are found in the given URL "https://www.metacritic.com/browse/movies/genre/date?page=0”开头的网址。
我做错了什么?
你的代码是正确的。
该列表保持为空,因为该页面上没有任何与该模式匹配的 URL。请尝试 re.compile("^/movie/")
。
首先,您应该使用标准库 "html.parser" 而不是 "xml" 来解析页面内容。它更好地处理损坏的 html(参见 Beautiful Soup findAll doesn't find them all)
然后看一下你正在解析的页面的源代码。您要查找的元素如下所示:<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)
我试过这段代码,但带有 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)
我想抓取所有以“https://www.metacritic.com/movie/" that are found in the given URL "https://www.metacritic.com/browse/movies/genre/date?page=0”开头的网址。
我做错了什么?
你的代码是正确的。
该列表保持为空,因为该页面上没有任何与该模式匹配的 URL。请尝试 re.compile("^/movie/")
。
首先,您应该使用标准库 "html.parser" 而不是 "xml" 来解析页面内容。它更好地处理损坏的 html(参见 Beautiful Soup findAll doesn't find them all)
然后看一下你正在解析的页面的源代码。您要查找的元素如下所示:<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)