【问题标题】:AttributeError in getText methodgetText 方法中的 AttributeError
【发布时间】: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


【解决方案1】:

请用此行更正您的代码行

final_soup.find('div', attrs={'class': 'someClass_2)

用这条线

final_soup.find('div', {'class': 'someClass_2'})

你错过了“'}”

【讨论】:

  • 对不起,这是一个类型错误。问题依旧,是不是有问题
  • 完整代码需要chromedriver才能工作,你可以只检查下面的代码final_soup = BeautifulSoup(self.driver.page_source, 'lxml')。同时导入:#coding=utf8, from bs4 import BeautifulSoup
  • 从您的代码中我可以理解的是,您的代码无法获取具有给定属性的任何“div”标签,因此它返回 None。
  • 您在查找功能中遗漏了两个字符 ' 和 }。请检查您是否写得正确或仍有错字?
  • 当然,可能是 div 标签或 div.h1 标签,但搜索特定项目的链接时,它有两个标签。请记住,这仅在我的脚本运行时发生。
【解决方案2】:

这段代码完成了我需要的工作。看起来该错误可能来自意外的 Internet 断开连接或服务器没有响应。

 while True:
            try:
                title = final_soup.find('div', attrs={'class': 'someclass'})
                sleep(1)
                origin_title = title.h1.getText()
                print(origin_title)
            except Exception as ex:
                print('number of try', i)
                sleep(1)
                i += 1
                continue
            break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2013-11-06
    • 2021-03-24
    相关资源
    最近更新 更多