BeautifulSoup和请求模块非类型错误



我已经尝试了几天请求和bs4模块。我想做一个简单的程序,类似于谷歌的"我感觉很幸运"。

这是我的代码:

import requests, bs4, webbrowser
source=requests.get('https://www.google.com/search?q=facebook').text
exsoup=bs4.BeautifulSoup(source, 'lxml')
# <cite class="iUh30">https://www.facebook.com/</cite>
match=exsoup.find('cite', class_='iUh30')
print(match.text)

但是当我运行这个时,我会得到以下错误:

print(match.text)
AttributeError: 'NoneType' object has no attribute 'text'

我怎样才能做到这一点?

尝试迭代类似的内容,不包括class_属性:

match=exsoup.find_all('cite')
for i in match:
if 'http' in i.text:
print(i.text)

问题似乎是,使用浏览器访问网站与使用请求库访问网站的结果不同。您可以尝试指定一个标头(我从下面的例子中得到了这个例子:https://stackoverflow.com/a/27652558/9742036)

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
source = requests.get('https://www.google.com/search?q=facebook', headers=headers).text

并且源代码看起来应该更像您的浏览器访问。

否则,您的代码运行良好。您只是在最初的命中中没有得到结果,所以应该编写代码来处理这种情况(例如,在另一个答案中使用迭代器建议(

相关内容

最新更新