【问题标题】:Scrape URLs using BeautifulSoup in Python 3在 Python 3 中使用 BeautifulSoup 抓取 URL
【发布时间】:2019-05-23 12:20:52
【问题描述】:

我尝试了此代码,但包含 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)

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

我做错了什么?

【问题讨论】:

    标签: python python-3.x beautifulsoup urllib


    【解决方案1】:

    首先您应该使用标准库“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)
    

    【讨论】:

    • 非常感谢。还有一个问题,因为您似乎擅长正则表达式:我如何省略所有不像“/movie/movie-name”的 URL,例如“/电影/电影名称/预告片”。我试过 "re.compile("^/movie/.+[^\/]")" 但他保留了所有不需要的 URL。
    • 您可以使用“^/movie/([a-zA-Z0-9\-])+$”之类的正则表达式来匹配“/movie/”之后仅包含字母、数字和减号的链接"
    • if '/trailers/' not in link.get('href'): links.append(link.get('href'))
    【解决方案2】:

    你的代码是正确的。

    该列表保持为空,因为该页面上没有任何 URL 与该模式匹配。请改用re.compile("^/movie/")

    【讨论】:

    • @leiropi 是对的,features="xml" 也在给你带来问题。 soup = BeautifulSoup(html_page, 'lxml') 确实给出了正确的结果。
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2019-06-03
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2018-04-15
    相关资源
    最近更新 更多