【问题标题】:BS4: AttributeError: 'NoneType' object has no attribute 'text'BS4:AttributeError:“NoneType”对象没有属性“文本”
【发布时间】:2019-02-09 16:01:58
【问题描述】:

我在尝试抓取某个职位发布网站时遇到问题。首先,我的网址在 CSV 文件“urls.csv”中

通常代码运行良好,但有时我会收到此错误:“AttributeError: 'NoneType' object has no attribute 'text'”,有时在 1 次迭代之后,有时在 30 次之后。如果问题出在假设 i=230,如果我再次运行它,它会很好地解析该 url,并在一些迭代后再次停止。

有人可以建议吗? 谢谢!

另外,错误发生在 textoffer = ......行上

编辑:链接到 csv:https://github.com/DonCheiron/Scraping-Be.Indeed/blob/master/urls.csv

import bs4 as bs
import urllib.request
import csv

with open('C:/Users/******/Desktop/urls.csv', 'r') as f:
    reader = csv.reader(f)
    pages = list(reader)
    for i in range (0,300):
        page = ''.join(map(str, pages[i]))
        print('Working on ' + str(i)+ "...")
        sauce = urllib.request.urlopen(page).read()
        soup =bs.BeautifulSoup(sauce,'lxml')
        textoffer = soup.body.div.find('div',class_='jobsearch-JobComponent-description icl-u-xs-mt--md').text
        file = open(str(i)+ '.txt','w')
        file.write(textoffer)
        file.close()
        print(str(i) + " Done!")

【问题讨论】:

  • 您需要使用tryexpection 来跳过for 循环中的错误而不是它之外的错误。
  • 尝试将with stmt 与for stmt 分开。
  • 似乎某些 URL 没有 'class' 组件,因此它返回 Nonetype。您可能希望添加异常,以便代码在包含class 组件的链接上运行。
  • 谢谢@Soumithri Chilakamarri。但是如果我第二次运行它怎么会找到类组件。另外,我手动检查了一下,确实有类组件。

标签: python-3.x


【解决方案1】:

使用您提供的一些随机网址,我尝试:

with open('urls.csv', 'r') as f:
    reader = csv.reader(f)
    pages = list(reader)
for counter, url in enumerate(pages):
    print(counter, ''.join(url))
    page_response = requests.get(''.join(url))
    print(page_response)
    soup = BeautifulSoup(page_response.content, 'html.parser')
    print(soup.body.div.find('div',class_='jobsearch-JobComponent-description icl-u-xs-mt--md')).text

输出:

0 https://be.indeed.com/rc/clk?jk=39582947a2d91970&fccid=adb55a49f6636f0e&vjs=3
<Response [200]>

None
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-511-2b829cd9fc45> in <module>()
      4     print(page_response)
      5     soup = BeautifulSoup(page_response.content, 'html.parser')
----> 6     print(soup.body.div.find('div',class_='jobsearch-JobComponent-description icl-u-xs-mt--md')).text
      7
      8

AttributeError: 'NoneType' object has no attribute 'text'

Traceback 非常清楚地向您展示了在没有找到任何内容时尝试将 find 转换为 text 是一个问题。至于为什么同一个 url 有时只会有这个类,它要么不是同一个 url,要么是一个不总是包含相同元素的动态页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多