【发布时间】:2018-09-25 10:25:10
【问题描述】:
当我抓取时,一切都很顺利,但有时当我抓取很多信息时 我明白了
AttributeError:“NoneType”对象没有属性“h1”。 以下是我的代码:
for index, link in enumerate(all_links):
self.driver.execute_script("window.open('" + link + "');")
print(link)
sleep(9)
self.driver.switch_to.window(self.driver.window_handles[1])
final_soup = BeautifulSoup(self.driver.page_source, 'lxml')
image = final_soup.find('div', attrs={'class': 'someClass_1'})
filename = 'image_' + str(index) + '.png'
title = final_soup.find('div', attrs={'class': 'someClass_2'})
sleep(1)
origin_title = title.h1.getText() # here is the problem
print(origin_title)
有时会出现此错误,奇怪的是我检查了特定链接的 html 并且所有链接看起来都与其他链接相同,我不知道为什么会出现错误。h1 标记中的文本在那里。
我尝试增加睡眠,但没有任何改变。我可以做的另一件事是添加 try - catch:
try:
origin_title = title.h1.getText() # here is the problem
print(origin_title)
except AttributeError:
pass
但我的问题是,如果在 h1 标记中找不到文本,我不想通过,文本就在那里,我应该以某种方式得到它
【问题讨论】:
-
你检查编码了吗?
-
#coding=utf8,我的脚本中有这个
-
您能否提供您尝试抓取的链接以获得更好的帮助?
标签: python-3.x web-scraping beautifulsoup gettext