【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' - BeautifulSoup to CSVAttributeError:“NoneType”对象没有属性“文本”-BeautifulSoup 到 CSV
【发布时间】:2021-01-12 23:35:32
【问题描述】:

我正在尝试制作一个浏览多个页面的网络爬虫,以便为我制作一个 csv 列表。当我运行它的基本代码时,它可以工作,但是当我让它迭代到多个页面时,我得到一个 AttributeError:

assignees=assignees_elem.text.strip() AttributeError: 'NoneType' 对象没有属性 'text'

csv 已保存但为空白。

这是我的代码:

import requests
from bs4 import *
import csv


pagenumber = 0


file = open('newcsv', 'w')
writer = csv.writer(file)

while pagenumber <50:
    pagenumber += 1
    pagenumbers = str(pagenumber)
    
    URL = 'website'+pagenumbers
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    site_elems = soup.find_all('div', class_='meta')
    writer.writerow(['Number', 'Issued', 'Assignees', 'Inventors'])
    
    for site_elem in site_elems:
        number_elem = site_elem.find('div', class_='number')
        issued_elem=site_elem.find('div', class_='date-issued')
        assignees_elem=site_elem.find('div', class_='assignees')
        inventors_elem=site_elem.find('div', class_='inventors')
        number=number_elem.text.strip()
        issued=issued_elem.text.strip()
        assignees=assignees_elem.text.strip()
        inventors=inventors_elem.text.strip()
        print (number + ' ' + issued +' ' + assignees + ' ' + inventors)
        writer.writerow([number.encode('utf-8'),issued.encode('utf-8'), assignees.encode('utf-8'),inventors.encode('utf-8')])
        
file.close()    

【问题讨论】:

  • 看来assignees_elem=site_elem.find('div', class_='assignees')什么也得不到。
  • 我通过添加if None in (number_elem, issued_elem, assignees_elem, inventors_elem): continue解决了它

标签: python beautifulsoup python-requests attributeerror html-parser


【解决方案1】:

我通过添加解决了它

if None in (number_elem, issued_elem, assignees_elem, inventors_elem): continue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多