【问题标题】:Why can't I find html tag when I scrape web using BeautifulSoup?为什么我使用 BeautifulSoup 抓取网页时找不到 html 标签?
【发布时间】:2022-01-11 02:19:14
【问题描述】:

我正在使用 BeautifulSoup 抓取一个网站,但 html 的输出与通过网络浏览器在页面源上显示的不匹配。缺少一些标签。以下是我的代码:

URL = '<url>'
response = requests.get(URL, headers = header)
html_doc = BeautifulSoup(response, 'html.parser')
content = html_doc.find('div', attrs={'class':'content-wrapper'})

我不确定发生了什么,但它可能与事件监听器有关。我在页面源的这个标签之后找到它。

【问题讨论】:

  • 可以分享你要抓取的网页的url吗?

标签: python html web-scraping beautifulsoup


【解决方案1】:

如果问题是由事件监听器引起的,我建议你使用beautifulsoupselenium来抓取这个网站。所以,让我们在发送请求时应用selenium 并返回页面源,然后使用beautifulsoup 解析它。

请注意,使用 selenium 需要浏览器驱动程序。您可以通过此链接 (https://www.selenium.dev/documentation/getting_started/installing_browser_drivers/) 找到。

使用Firefox的代码示例:

from selenium import webdriver

URL = '<url>'
browser = webdriver.Firefox()
browser.get(URL)
html_doc = BeautifulSoup(browser.page_source, 'html.parser')
time.sleep(1)
browser.close()

content = html_doc.find('div', attrs={'class':'content-wrapper'})

【讨论】:

    猜你喜欢
    • 2019-09-25
    • 2020-11-29
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2020-07-16
    • 2022-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多