[英]I am getting error like AttributeError: 'NoneType' object has no attribute 'text'
import pandas as pd
import requests
from bs4 import BeautifulSoup
page = requests.get('https://www.adityaispat.com/vision-mission.html', verify=False)
#url = "https://www.aarti-industries.com/csr/"
#page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
print(soup.find(class_="text").text)
or
print(soup.find('td', attrs={'class': 'text'}).text)
Simple answer to your question is that find()
method returns object of type NoneType
and you're trying to read text
from it.对您的问题的简单回答是
find()
方法返回类型为 NoneType 的NoneType
并且您正在尝试从中读取text
。 To prevent this, it's worth to check first if find()
gives any result.为了防止这种情况,首先检查
find()
是否给出任何结果是值得的。
result = soup.find(class_="text")
if result:
print(result.text)
else
# other action
Another answer is question: what you're trying to find?另一个答案是问题:你想找到什么? Maybe your class and/or atrributes to search are defined incorrectly.
也许您的 class 和/或搜索属性定义不正确。
I in your case the true source of problem is request
part.我在你的情况下,问题的真正根源是
request
部分。 If you check page.status_code
, you'll notice that it returns 406, that means request was unseccessful.如果您检查
page.status_code
,您会注意到它返回 406,这意味着请求不成功。 Basing on this solution you need to use a different User-Agent.基于此解决方案,您需要使用不同的用户代理。 Also remember to check if request was successful.
还要记得检查请求是否成功。 Siplme way is to use
ok
property. Siplme 方法是使用
ok
属性。
page = requests.get('https://www.adityaispat.com/vision-mission.html', headers={"User-Agent": "XY"})
if page.ok:
print('Request OK!')
# process the page
else:
print('Request Failed!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.