python - 我收到 AttributeError : 'NoneType' object has no attribute 'find'

标签 python web-scraping

您好,这是我的代码,用于检索 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/

相关文章:

python - 如何抑制 IPython 启动消息?

html - 如果我有一组随机网站,我如何从每个网站获取特定信息?

javascript - HtmlUnit 没有创建 HtmlPage 对象

python - ValueError : Expected singleton: res. 合作伙伴(1, 12, 29, 30, 36) - res.partner - Odoo v10 社区

python - 使用 Python 进行网页抓取

python - 在特定文本之后和特定文本之前刮取文本

python - 使用 Selenium Scraper 删除符号 (Python)

python - Pandas max() 和 min() 工作,但 Mean() 给出 "No numeric types"错误

python - 编程错误 : Wrong number of arguments during string formatting

python - 如何在选项旁边渲染表单 ChoiceField 图像而不破坏表单?