社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

AttributeError:“NoneType”对象没有属性“text”。用Python进行Web抓取[duplicate]

Scott Geilen • 4 年前 • 311 次点击  

我对这个网站上发布的另一个问题没有任何把握。 目标 确实是.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())

错误日志:

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

我正试着从Really.com搜集代码:

<span class="salaryText">
$15 - $30 an hour</span>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54703
 
311 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Srivats Shankar
Reply   •   1 楼
Srivats Shankar    4 年前

答案相对简单。您需要查看您试图擦掉的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())