【问题标题】:Python AttributeError NoneType 'text'Python AttributeError NoneType '文本'
【发布时间】:2018-01-27 20:42:32
【问题描述】:

尝试制作一个 Python 脚本,该脚本可以从页面的 pastebin 的 RAW Paste Data 部分中抓取保存的 pastebin 输出。但是我遇到了 Python Attribute Error about NoneType has no object attribute 'text' 的问题,我在我的项目中使用来自 BeautifulSoup 的库。我尝试使用pip install 安装spider-egg,这样我也可以使用它,但是从服务器下载软件包时出现问题。

我需要能够从 RAW Paste Data 部分抓取不同的多行并将它们打印回给我。

first_string = raw_box.text.strip()
second_string = raw_box2.text.strip()

在 pastebin 页面中,我有 RAW Paste Data 部分的类元素名称;

<textarea id="paste_code" class="paste_code" name="paste_code" onkeydown="return catchTab(this,event)">

取班级名称paste_code然后我就有了这个

raw_box = soup.find('first_string ', attrs={'class': 'paste_code'})
raw_box2 = soup.find('second_string ', attrs={'class': 'paste_code'})

我认为应该是这样,但显然不是,因为我得到了我之前提到的错误。解析已被剥离的数据后,我需要能够在打印得到的数据后将其重定向到文件中。我也想尝试使这个 python3 兼容,但我认为这需要更多的工作,因为 python 2.7.12 和 3.5.2 之间存在很多差异。

【问题讨论】:

  • 该特定错误告诉您raw_box 变量之一是None,这意味着您尝试find 的字符串不存在(至少,不是那种您正在搜索的元素)。可能没有找到任何匹配项是预期的情况,在这种情况下,您可能应该进行if raw_box is None 检查并以不同的方式处理该情况。如果出现意外情况,您需要进一步调查以找出您未获得预期结果的原因(我们无法真正帮助您提供有限的信息)。

标签: python web-scraping beautifulsoup scrapy


【解决方案1】:

以下方法应该有助于您入门:

import requests    
from bs4 import BeautifulSoup

r = requests.get('https://pastebin.com/hGeHMBQf')
soup = BeautifulSoup(r.text, "html.parser")
raw = soup.find('textarea', id='paste_code').text

print raw

本例应显示的内容:

hello world

【讨论】:

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