![](/img/trans.png)
[英]I'm facing this AttributeError: 'NoneType' object has no attribute 'compile'
[英]I'm getting AttributeError: 'NoneType' object has no attribute 'find'
嗨,这是我的代码,用于检索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.prettify()
,但你可以取消注释它并查看它的作用 - 它以一种组织良好的方式向你显示页面的源代码。
错误的来源是......
来自Beautiful Soup文档 - 如果find()
找不到任何内容,则返回None
。
由于拼写错误,它肯定无法找到您想要的centre
标签。
此外,您将要从较低级别删除data
,因为第一级已经返回Tag元素对象.. level2= level1.find('table',attrs = {'id':'hnmain'})
我仍然在3级之后被抓住了...我掠过返回值并且tbody
没有出现在任何地方..所以我不确定树实际上是在哪里突然转向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.