我一直在努力学习Python(目前的请求和beautifulsoup4),我找到了一个教程online
问题是我一直收到以下错误,根本无法弄明白......
任何帮助将不胜感激!
追踪(最近一次通话): 文件“C:\ Users \ BillyBob \ Desktop \ Web Scrap.py”,第14行,in title = 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']
答案 0 :(得分:4)
如果一个标签包含多个东西,那么不清楚.string应该引用什么,所以.string被定义为None
我相信你可以使用.text
来获得你想要的东西:
title = a.text.strip()
答案 1 :(得分:4)
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']
这样,在调用关联方法之前,会明确检查每个参数。