Python AttributeError: 'NoneType' 对象没有属性 'strip'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41203823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:34:05  来源:igfitidea点击:

AttributeError: 'NoneType' object has no attribute 'strip'

python

提问by Ctsa3

I've been trying to learn Python (currently requests and beautifulsoup4) and I found a tutorial online

我一直在尝试学习Python(目前是requests和beautifulsoup4),我在网上找到了一个教程

The issue is I keep getting the below error and cannot figure it out at all...

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

Any help would be appreciated!

任何帮助,将不胜感激!

Traceback (most recent call last): File "C:\Users\BillyBob\Desktop\Web Scrap.py", line 14, in title = a.string.strip() AttributeError: 'NoneType' object has no attribute 'strip'

回溯(最近一次调用):文件“C:\Users\BillyBob\Desktop\Web Scrap.py”,第 14 行,标题 = a.string.strip() AttributeError: 'NoneType' object has no attribute 'strip'

Here is my code in case I made a mistake;

这是我的代码,以防我犯了错误;

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']

回答by Yevhen Kuzmovych

From BS4 documentation:

来自BS4 文档

If a tag contains more than one thing, then it's not clear what .string should refer to, so .string is defined to be None

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

I believe you can use .textto get what you want:

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

title = a.text.strip()

回答by finbarr

The first member of samplesdoes not have a string attribute, and as a result, a.stringdoesn't return anything, so you're calling the strip()method on something that doesn't exist.

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

However, then you have another problem; it is not necessarily true that ahas the hrefattribute. Instead, you should check explicitly for both, or else you will get errors (which is the problem with Yevhen's answer, which is otherwise correct).

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

One potential fix to your problem is to write:

解决您的问题的一种可能方法是编写:

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']

This way, you check explicitly for each parameter before calling the associated method.

这样,您可以在调用关联方法之前明确检查每个参数。