【问题标题】:AttributeError: 'NoneType' object has no attribute 'text'. Web scraping indeed with Python [duplicate]AttributeError:“NoneType”对象没有属性“文本”。确实使用 Python 进行 Web 抓取 [重复]
【发布时间】:2020-05-14 13:14:05
【问题描述】:

我对本网站上发布的其他问题没有任何运气。 我对这个程序的目标是从 Indeed.com 上抓取招聘信息。我遇到了属性错误。我不知道为什么会收到此错误,因为我要确保 HTML 和 Python 之间的标签匹配。谁能帮我解决这个问题?

代码:

import urllib.request as urllib
from bs4 import BeautifulSoup
import csv

# empty array for results
results = []

# initialize the Indeed URL to url string
url = 'https://www.indeed.com/jobs?q=software+developer&l=Phoenix,+AZ&jt=fulltime&explvl=entry_level'
soup = BeautifulSoup(urllib.urlopen(url).read(), 'html.parser')
results = soup.find_all('div', attrs={'class': 'jobsearch-SerpJobCard'})

for i in results:
    title = i.find('div', attrs={"class":"title"})
    print('\ntitle:', title.text.strip())

    salary = i.find('span', attrs={"class":"salaryText"})
    print('salary:', salary.text.strip())

    company = i.find('span', attrs={"class":"company"})
    print('company:', company.text.strip())

错误日志:

Traceback(最近一次调用最后一次):文件“c:/Users/Scott/Desktop/code/ScrapingIndeed/index.py”,第 16 行,在 print('salary:',salary.text.strip())
Scott@DESKTOP-MS37V5T MINGW64 ~/Desktop/code
$ AttributeError: 'NoneType' 对象没有属性 'text'

我正在尝试抓取来自 Indeed.com 的代码:

<span class="salaryText">
$15 - $30 an hour</span>

【问题讨论】:

  • 你好 Scott,请提供最小的工作示例,我们这里不使用截图。
  • 请提供完整的错误日志,加上在一些 scpp 字段中,你没有得到完整的数据,即你是空的,你需要处理它

标签: python web-scraping attributeerror


【解决方案1】:

答案比较简单。您需要查看您尝试抓取的 HTML 的源代码。

并非所有div 实体都有您要查找的工资信息。因此,您运行的一些搜索返回了 Python 所指的 None 值实体。无法打印,尽管您可以对其进行操作。

您需要做的就是检查工资信息的值是否是可打印值。

例如看看下面修改的代码:

    salary = i.find('span', attrs={"class":"salaryText"})
    if salary is not None:
      print('salary:', salary.text)

整个代码如下:

import urllib.request as urllib
from bs4 import BeautifulSoup
import csv

# empty array for results
results = []

# initialize the Indeed URL to url string
url = 'https://www.indeed.com/jobs?q=software+developer&l=Phoenix,+AZ&jt=fulltime&explvl=entry_level'
soup = BeautifulSoup(urllib.urlopen(url).read(), 'html.parser')
results = soup.find_all('div', attrs={'class': 'jobsearch-SerpJobCard'})

for i in results:
    title = i.find('div', attrs={"class":"title"})
    print('\ntitle:', title.text.strip())

    salary = i.find('span', attrs={"class":"salaryText"})
    if salary is not None:
      print('salary:', salary.text)

    company = i.find('span', attrs={"class":"company"})
    print('company:', company.text.strip())

【讨论】:

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