如何修复 AttributeError: 'NoneType' 对象没有属性 'text'...循环时

2023-11-29

我是初学者,这个论坛上的答案非常宝贵。我正在使用 Python 3 和 Beautiful Soup 通过循环页码从同一网站上的多个网页中抓取(非表)数据。它有效,但我不断收到 AttributeError: 'NoneType' object has no attribute 'text' 第一次迭代后。

这是我迄今为止尝试过的代码:

import requests

from bs4 import BeautifulSoup

import csv

import lxml


# Lists to store the scraped data in

addresses = []
geographies = []
rents = []
units = []
availabilities = []

# Scraping all pages

pages_url = requests.get('https://www.rent.com/new-york/tuckahoe-apartments')

pages_soup = BeautifulSoup(pages_url.text, 'html.parser')

list_nums = pages_soup.find('div', class_='_1y05u').text

print(list_nums)

pages = [str(i) for i in range(1,8)]

for page in pages:

    response = requests.get('https://www.rent.com/new-york/tuckahoe-apartments?page=' + page).text

    html_soup = BeautifulSoup(response, 'lxml')


    # Extract data from individual listing containers

    listing_containers = html_soup.find_all('div', class_='_3PdAH')
    print(type(listing_containers))
    print(len(listing_containers))



    for container in listing_containers:
        address = container.a.text
        addresses.append(address)

        geography = container.find('div', class_='_1dhrl').text
        geographies.append(geography)

        rent = container.find('div', class_='_3e12V').text
        rents.append(rent)

        unit = container.find('div', class_='_2tApa').text
        units.append(unit)

        availability = container.find('div', class_='_2P6xE').text
        availabilities.append(availability)

        import pandas as pd
        test_df = pd.DataFrame({'Street' : addresses,
                                'City-State-Zip' : geographies,
                                'Rent' : rents,
                                'BR/BA' : units,
                                'Units Available' : availabilities

        })
        print(test_df)

这是输出:

240 Properties
<class 'bs4.element.ResultSet'>
30
                     Street                      City-State-Zip     Rent                 BR/BA    Units Available
0  Quarry Place at Tuckahoe  64 Midland PlaceTuckahoe, NY 10707  $2,490+  1–2 Beds • 1–2 Baths  2 Units Available
Traceback (most recent call last):
  File "renttucktabletest.py", line 60, in <module>
    availability = container.find('div', class_='_2P6xE').text
AttributeError: 'NoneType' object has no attribute 'text'

我正在寻找的结果是pandas 数据框中的所有 240 个列表与上面输出中显示的第一次迭代完全相同。任何人都可以帮助修复这个错误吗?将不胜感激。谢谢你!


正如所指出的,问题是一些容器缺少某些div元素。例如,没有“单位”或“可用性”信息。

解决这个问题的一种方法是使用if - else声明。仅当元素存在时追加,否则追加NaN价值。就像是:

import requests
import numpy as np
from bs4 import BeautifulSoup

import csv

import lxml


# Lists to store the scraped data in

addresses = []
geographies = []
rents = []
units = []
availabilities = []

# Scraping all pages

pages_url = requests.get('https://www.rent.com/new-york/tuckahoe-apartments')

pages_soup = BeautifulSoup(pages_url.text, 'html.parser')

list_nums = pages_soup.find('div', class_='_1y05u').text

print(list_nums)

pages = [str(i) for i in range(1,8)]

for page in pages:

    response = requests.get('https://www.rent.com/new-york/tuckahoe-apartments?page=' + page).text

    html_soup = BeautifulSoup(response, 'lxml')


    # Extract data from individual listing containers

    listing_containers = html_soup.find_all('div', class_='_3PdAH')
    print(type(listing_containers))
    print(len(listing_containers))



    for container in listing_containers:
        address = container.a
        if address:
            addresses.append(address.text)
        else:
            addresses.append(np.nan)

        geography = container.find('div', class_='_1dhrl')
        if geography:
            geographies.append(geography.text)
        else:
            geographies.append(np.nan)

        rent = container.find('div', class_='_3e12V')
        if rent:
            rents.append(rent.text)
        else:
            rents.append(np.nan)

        unit = container.find('div', class_='_2tApa')
        if unit:
            units.append(unit.text)
        else:
            units.append(np.nan)

        availability = container.find('div', class_='_2P6xE')
        if availability:
            availabilities.append(availability.text)
        else:
            availabilities.append(np.nan)

import pandas as pd
test_df = pd.DataFrame({'Street' : addresses,
                        'City-State-Zip' : geographies,
                        'Rent' : rents,
                        'BR/BA' : units,
                        'Units Available' : availabilities

})
print(test_df)

                     Street                      City-State-Zip     Rent  \
0  Quarry Place at Tuckahoe  64 Midland PlaceTuckahoe, NY 10707  $2,490+   
1     address not disclosed                  Tuckahoe, NY 10707   $2,510   
2     address not disclosed                  Tuckahoe, NY 10707   $4,145   
3        60 Washington St 1  60 Washington StTuckahoe, NY 10707   $3,500   
4        269 Columbus Ave 5  269 Columbus AveTuckahoe, NY 10707   $2,700   

                  BR/BA    Units Available  
0  1–2 Beds • 1–2 Baths  2 Units Available  
1        1 Bed • 1 Bath                NaN  
2       2 Beds • 2 Bath                NaN  
3       3 Beds • 2 Bath                NaN  
4       2 Beds • 1 Bath                NaN 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何修复 AttributeError: 'NoneType' 对象没有属性 'text'...循环时 的相关文章

随机推荐

  • Delphi 中重复直到中使用的函数 Sleep() 的奇怪行为

    我的功能是单击按钮时的反应 当我单击按钮时 它应该开始重复并写入数组中的值 并将它们显示在主窗体的标签中 问题在于功能睡眠 有一些错误或其他原因 因为当我单击按钮时 它等待了很长一段时间 然后它最终开始执行操作 但速度很快 让我们看看我的代
  • JavaScript 缩放整个 Div

    我正在寻找一个可以放大整个 div 的 JQuery 脚本 我找到了以下插件 http test dpetroff ru jquery iviewer test and 这些插件正是我需要的东西 只需用滚轮放大和缩小 但我有一个问题 我需要
  • npm install 在出现如此多的警告后给出错误

    我的 ReactJS 项目直到上周都运行良好 但从周日开始 它在 npm install 上出现以下错误 PS C Projects Interface ClientApp gt npm install npm WARN deprecate
  • 如何使用IpropertyStorage读取文件的属性?

    如何使用 iPropertyStorage 读取文件的属性 如标题 作者 页数等 谁知道c 中的代码请发布它 实际上 我正在尝试以编程方式 使用 c 读取文件属性 标题 摘要 作者 注释等 当您看到文件的属性时 摘要 选项卡上显示的内容 F
  • 事务回滚,但插入一条记录

    大家好 我已经使用 jsf spring 3 0 hybernate JPA 和atomikos 进行了 XA 交易管理 mysql 是我的后端 这里一切正常 但是插入操作 当异常抛出时 交易应该回滚 但是它没有发生 这是我们应用程序的一个
  • 使用jquery附加vue js组件

    我正在尝试动态附加vue使用 jquery 将组件添加到我的应用程序中 但什么也没有发生 附加元素没有渲染 div div 我想要的结果是附加时
  • HSM 和自定义模块

    我们正在实施安全关键系统 其中FIPS 140 2需要兼容的 HSM 硬件安全模块 来生成和存储密钥材料 执行加密 解密以及运行自定义代码 并为自定义模块设置以下要求 模块可通过 RPC 访问 模块可以访问所有 HSM 密钥和服务 模块具有
  • php shell命令错误GLIBCXX_3.4.9未找到

    我试图从 php 执行 shell 命令将文件转换为 pdf 但出现此错误 有人可以详细解释我如何修复它吗 我不太擅长linux 而且 如果我直接通过终端执行命令 一切都会正常 usr lib libreoffice program oos
  • 我为什么可以在 std::vector 中使用前向声明的类?

    我认为您只能创建指向前向声明类的引用或指针成员 然而 我惊讶地发现这个有效 include
  • 在 GAE 上使用 boto3 - 遇到 Popen 问题

    我正在尝试在 Google App Engine 中运行一些 python 代码 该代码向 Amazon SQS 发送消息 我已经安装了 boto3 但在尝试将其导入我的 AppEngine 服务时遇到错误 File base data h
  • 使用 R 中的 Match 函数查找“第一次出现”

    我是 R 和 Stackoverflow 的新手 所以请原谅我提出这个非常基本的问题 我正在尝试在我的数据集中找到第一个女性的 索引 代码快照 我的整个数据集称为 自行车 所以首先我认为分配一个仅包含性别的新向量是个好主意 bike gen
  • 使用填充堆叠不同长度的 Numpy 数组

    a np array 1 2 3 b np array 4 5 l a b 我想要一个功能stack padding这样 assert stack padding l np array 1 2 3 4 5 0 numpy 是否有实现的标准方
  • Prolog 将分钟转换为小时

    这是我创建的代码 mins to hours In H M In lt 60 H 0 M is In mins to hours In H M In gt 60 H is H1 1 In1 is In 60 mins to hours In
  • jQuery AJAX 请求 302 重定向 - 哪些回调可用?

    我正在使用一个使用 jQuery 1 2 6 的旧系统 我正在通过以下方式发送 AJAX 请求jQuery ajax功能 它所访问的 URL 正在发送 302 HTTP 重定向响应 并最终以 200 HTTP OK 响应结束 我已经注册了两
  • 如何将 $SHELL 变量传递到 perl 搜索和替换中

    我有以下两个命令 value grep o Logs txt textFILE perl i wpe s onclick img document getElementById img 1 img style display img sty
  • ftplib.FTP 超时行为不一致

    我正在尝试使用ftplib FTP 使用超时选项作为特定主机名的超时值 但我遇到了奇怪的行为 为了测试它 我编写了一段非常简单的代码 import ftplib from ftplib import FTP ftp ftplib FTP g
  • 将表达式作为参数传递:关键字不能是表达式

    这是我的行动 gt gt gt def show d print d gt gt gt test result True gt gt gt show test result True gt gt gt show test info Some
  • 使用 SDL 2 和 -static 进行编译时收到对各种 Windows 库的未定义引用?

    我正在对 SDL2 中的 Wolfenstein 3D 引擎进行修改 使用 Wolf4SDL 作为基础 并且遇到了一个问题 在链接器选项中使用 static 时 我得到了对各种事物的大量未定义引用 这是我的构建日志来说明我的意思 Build
  • 将数据集动态绑定到 RDLC 报告

    我想将动态数据集绑定到 rdlc 如果我在 ASPX 文件中使用内联数据源 静态绑定 我可以查看报告 但是 如果我使用以下代码 报告查看器将继续显示 正在加载 图像 我已经检查了数据集名称 如果我将数据集名称更改为 Orders2 它会显示
  • 如何修复 AttributeError: 'NoneType' 对象没有属性 'text'...循环时

    我是初学者 这个论坛上的答案非常宝贵 我正在使用 Python 3 和 Beautiful Soup 通过循环页码从同一网站上的多个网页中抓取 非表 数据 它有效 但我不断收到 AttributeError NoneType object