您好,这是我的代码,用于检索 ycombinator
网站中的第一个主题。当我运行代码时,我得到-
AttributeError: 'NoneType' object has no attribute 'find'for the line
level2= data.level1.find('table',attrs = {'id':'hnmain'})
主题深深地嵌套在各种标签中,这就是我按以下方式进行的原因。我这样做只是为了练习,所以我知道这可能不是我第一天编码的最佳方式,我只想知道如何克服错误。
import requests
from bs4 import BeautifulSoup
response1= requests.get('https://news.ycombinator.com/')
response = response1.text
data = BeautifulSoup(response,"html.parser")
level1= data.body.find('centre')
level2= data.level1.find('table',attrs = {'id':'hnmain'})
level3= data.level2.find('tbody')
level4= data.level3.find('tr')
level5= data.level4.find('td')
level6= data.level5.find('table.itemlist')
level7= data.level6.find('tbody')
level8= data.level7.find('tr#15426209.athing')
level9= data.level8.find('td.title')
level10= data.level9.find('a.storylink')
print(level10.text)
最佳答案
我认为您收到错误是因为 data.body
部分。我从来没有见过这样做的。
这是您的代码的修改版本:
import requests
from bs4 import BeautifulSoup
r = requests.get('https://news.ycombinator.com')
soup = BeautifulSoup(r.text, 'lxml')
# print soup.prettify()
stories = []
for a in soup.find_all('a', attrs={'class': 'storylink'}):
stories.append([a.text, a['href']])
print stories[0]
[u'Using Binary Diffing to Discover Windows Kernel Memory Disclosure Bugs', 'https://googleprojectzero.blogspot.com/2017/10/using-binary-diffing-to-discover.html']
我已经注释掉了 soup.pretify()
,但您可以取消注释并查看它的作用 - 它以一种组织良好的方式向您显示页面的源代码。
关于python - 我收到 AttributeError : 'NoneType' object has no attribute 'find' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627234/