【问题标题】:Web scraping from Google Finance: returned data list always empty从 Google 财经抓取网页:返回的数据列表始终为空
【发布时间】:2019-11-05 06:36:21
【问题描述】:

我想使用 Python 的 BeautifulSoup 库从 Google 财经中抓取数据(例如,市值、市盈率等)。但是,当我尝试使用“find_all”功能从相应的 Google 财经网站的 html 代码中提取某些段落(如“div”、“tr”、“td”)时,我总是收到一个空列表(即,下面代码中的“base”对象为空)。

在调试过程中,我打印了“汤”对象并将其内容与相应的 html 代码进行比较。令我惊讶的是“汤”对象的内容与 html 代码的内容不同。我希望两者都应该匹配才能成功提取数据。

from bs4 import BeautifulSoup
import urllib.request

opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('https://www.google.com/search?q=NASDAQ:GOOGL')

soup = BeautifulSoup(response, 'html.parser')
base = soup.find_all('div',{'class':'ZSM8k'})

print(soup)
print(base)

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    它为你提供什么内容完全取决于服务器,所以你能做的最好的事情就是尽可能确保你的请求看起来像浏览器发送的请求。在您的情况下,这可能意味着:

    opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36')]
    

    如果我没记错的话,这会给你你想要的。如果需要,您可以尝试通过反复试验来删除不相关的部分。

    【讨论】:

    • 非常感谢!这解决了这个问题。你能解释一下为什么你的解决方案有效吗?
    • 我不确定;这正是我的 Chrome 浏览器在 HTTP 标头中发送的内容(可以在 Devtools 中看到)。看起来 Google 正在仔细检查 User-Agent 并相应地提供不同的 CSS,这无论如何都是有道理的。
    • 感谢您的补充说明。
    猜你喜欢
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    相关资源
    最近更新 更多