python - 美丽汤不会返回结果

标签 python beautifulsoup

这是我的代码。它不会返回任何错误,但也不会返回任何结果。

import requests
from bs4 import BeautifulSoup

googtrends = requests.get("https://www.google.com/trends/")
soup = BeautifulSoup(googtrends.content)
links = soup.find_all("a", {"class": "trending-story ng-isolate-scope"})

print links

我还没有解决这个问题,我开始做其他的事情,但我将首先尝试使用selenium,然后尝试将selenium与phantom js或zombie js一起使用,如果仍然不起作用,我将使用 pytrends,但我刚刚检查了它们,您需要一个 gmail 帐户,我有该帐户,但我宁愿先尝试让它在没有 api 的情况下工作。

当我开始工作时,我会在这里发帖

最佳答案

是的这个页面是由 JS 动态渲染的 - 让我们尝试一下更改请求 header (它失败了,同样确保 JS 是原因!)

测试代码-

import requests
from bs4 import BeautifulSoup


my_headers={"Host": "www.google.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,am;q=0.7,zh-HK;q=0.3",
"Accept-Encoding": "gzip, deflate",
"Cookie": "PREF=ID=1111111111111111:FF=0:LD=en:TM=1439993585:LM=1444815129:V=1:S=Zjbb3gK_m_n69Hqv; NID=72=F6UyD0Fr18smDLJe1NzTReJn_5pwZz-PtXM4orYW43oRk2D3vjb0Sy6Bs_Do4J_EjeOulugs_x2P1BZneufegpNxzv7rkY9BPHcfdx9vGOHtJqv2r46UuFI2f5nIZ1Cu4RcT9yS5fZ1SUhel5fHTLbyZWhX-yiPXvZCiQoW4FjZd-3Bwxq8yrpdgmPmf4ufvFNlmTd3y; OGP=-5061451:; OGPC=5061713-3:",
"Connection": "keep-alive"}


googtrends = requests.get("https://www.google.com/trends/",headers=my_headers)
my_content = googtrends.text.encode('utf-8')
soup = BeautifulSoup(my_content,'html.parser')
links = soup.find_all("a", {"class": "trending-story ng-isolate-scope"},href=True)

#Lets try if we are getting correct content from the site
# That site contains "Apple Inc.‬, ‪App Store‬‬" so let's check it in the got response

print 'Apple Inc.‬, ‪App Store‬‬' in my_content

# It prints false so website is being rendered by JS even header change does not affect

因此,请尝试在 Firefox、Chrome、PhantomJS 等中动态执行 JS 的 webdriver,例如 selenium。 更好地尝试 API。

关于python - 美丽汤不会返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132979/

相关文章:

python - Neo4J/py2neo——在事务中创建 `Relationship`?

python - 在 python 中使用 reduce() 序列化一个字符串

python - 如何提取一些 anchor 标签之间的文本?

python - 使用 Python 进行网页抓取有时会获取结果有时会导致 HTTP 429

python - 用Python计算文件中奇数和偶数的总数

python - 与 Python 3.0 的 SSH 连接

python - 如何使用 NetworkX 创建两个相同的图

python - 使用 bs4 webscraping 通过内容获取 HTML 类属性

python - 使用 Beautifulsoup 的带有空格的类的正则表达式

python - 如何使用自定义标记颜色将每个句子包装在标签中?