这是python代码,用于使用BeautifulSoup库从github存储库中抓取web内容。我面临错误:
"NoneType' object has no attribute 'text'"
在这个简单的代码中。我面临着2行代码中的注释错误。你知道吗
import requests
from bs4 import BeautifulSoup
import csv
URL = "https://github.com/DURGESHBARWAL?tab=repositories"
r = requests.get(URL)
soup = BeautifulSoup(r.text, 'html.parser')
repos = []
table = soup.find('ul', attrs = {'data-filterable-for':'your-repos-filter'})
for row in table.find_all('li', attrs = {'itemprop':'owns'}):
repo = {}
repo['name'] = row.find('div').find('h3').a.text
#First Error Position
repo['desc'] = row.find('div').p.text
#Second Error Postion
repo['lang'] = row.find('div', attrs = {'class':'f6 text-gray mt-2'}).find('span', attrs = {'class':'mr-3'}).text
repos.append(repo)
filename = 'extract.csv'
with open(filename, 'w') as f:
w = csv.DictWriter(f,['name','desc','lang'])
w.writeheader()
for repo in repos:
w.writerow(repo)
输出
Traceback (most recent call last): File "webscrapping.py", line 16, in repo['desc'] = row.find('div').p.text AttributeError: 'NoneType' object has no attribute 'text'
发生这种情况的原因是,当您通过BeautifulSoup查找元素时,它就像一个
dict.get()
调用。当您转到find
元素时,它将get
从元素树中删除它们。如果找不到,则返回Exception
,而不是一个None
。None
不具有Element
将具有的属性,如text
、attr
等。因此,当您在没有try/except
或没有验证类型的情况下进行Element.text
调用时,您就在打赌元素将始终存在。你知道吗我可能会先将给您带来问题的元素保存在一个temp变量中,这样您就可以进行类型检查了。或者实现
try/except
型式检验
尝试/例外
我个人倾向于try/except,因为它更简洁,异常捕捉是增强程序健壮性的一个很好的实践
你的
find
调用是不准确的,并且是链式的,所以当你试图找到一个<div>
标记,它没有p
子标记时,你得到了None
,但是你继续在None
上调用属性.text
,这会使你的程序崩溃。你知道吗请尝试以下一组
.find
调用,这些调用使用您要查找的itemProp
属性,并使用try-except
块以null合并任何缺少的字段:调试输出(除了写入的CSV):
相关问题 更多 >
编程相关推荐