【问题标题】:AttributeError: 'NoneType' object has no attribute 'strip'AttributeError:“NoneType”对象没有属性“strip”
【发布时间】:2017-05-03 09:31:45
【问题描述】:

我一直在努力学习Python(目前是requests和beautifulsoup4),找到了一个教程online

问题是我不断收到以下错误,根本无法弄清楚...

任何帮助将不胜感激!

Traceback(最近一次调用最后一次): 文件“C:\Users\BillyBob\Desktop\Web Scrap.py”,第 14 行,在 标题 = a.string.strip() AttributeError: 'NoneType' 对象没有属性 'strip'

这是我的代码,以防我出错;

import requests
from bs4 import BeautifulSoup

result = requests.get("http://www.oreilly.com/")

c = result.content

soup = BeautifulSoup(c, "html.parser")
samples = soup.find_all("a")
samples[0]

data = {}
for a in samples:
    title = a.string.strip()
    data[title] = a.attrs['href']

【问题讨论】:

  • string 的属性aNone。您需要查看 BeautifulSoup 的文档并查看 .find_all() 返回的内容。

标签: python


【解决方案1】:

来自BS4 documentation

如果一个标签包含多个东西,那么不清楚 .string 应该指什么,所以 .string 被定义为 None

相信你可以使用.text得到你想要的:

title = a.text.strip()

【讨论】:

    【解决方案2】:

    samples 的第一个成员没有字符串属性,因此,a.string 不返回任何内容,因此您正在对不存在的内容调用 strip() 方法。

    但是,您还有另一个问题; a 不一定具有 href 属性。相反,你应该明确地检查两者,否则你会得到错误(这是 Yevhen 的答案的问题,否则是正确的)。

    您的问题的一个潜在解决方法是编写:

    for a in samples:
        if not a.string is None:
            title = a.string.strip()
            if 'href' in a.attrs.keys():
                data[title] = a.attrs['href']
    

    这样,您可以在调用相关方法之前显式检查每个参数。

    【讨论】:

    • 好收获。虽然我认为主要问题是 OP 在所有链接中搜索标题 (.find_all("a"))。
    • 我同意这一点。我认为使用更有选择性的搜索会更多地帮助 OP,因为我的代码解决了这个问题。
    猜你喜欢
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2020-03-25
    • 2016-08-11
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多