【问题标题】:How to extract href attributes that show up on chrome's developer tools, but not on BeautifulSoup's output如何提取显示在 chrome 的开发人员工具上的 href 属性,而不是 BeautifulSoup 的输出
【发布时间】:2020-07-19 03:11:28
【问题描述】:

我正在尝试使用 Python 的 request 和 bs4 抓取一个网站来编译和总结新闻。我尝试访问的链接(href)出现在 Chrome 的开发者工具中,路径如下:

"/html/body/div/div/div/main/article/div/div/section/div/section/div/div[3]/ul/li[1]/a"

我尝试了所有方法来提取它们,但我意识到 Python 的 html 输出并没有下降到那个水平。它停留在:

"/html/body/div/div/div/main/article/div/div/section/div/section"

我正在使用以下代码:

import requests
from bs4 import BeautifulSoup
url = 'https://www.gp.com/news'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
for url in soup.find_all('a'):
    print(url.get('href'))

非常感谢您能给我的任何帮助,因为我完全没有想法。另外,我对编程完全陌生,因此希望您的答案尽可能地简单化。

提前非常感谢!

【问题讨论】:

    标签: python beautifulsoup python-requests href screen-scraping


    【解决方案1】:

    requests 模块不呈现 javascript -- 您必须使用 requests-html (https://github.com/psf/requests-html)。如果您在浏览器中打开页面然后查看源代码(通常是 CTRL-U),您可以看到差异。它将不同于您使用开发者工具查看的内容,因为后者包含由 javascript 呈现的内容。

    【讨论】:

    • 非常感谢 Eric 的分享。我不知道 requests-html 模块,并且请求本身无法获得全部内容。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 2010-10-25
    相关资源
    最近更新 更多