python - 对象没有属性“文本”
问题描述
好的,让我们再试一次。我正在抓取一个 xml 格式的网页。我正在收集我需要的东西,但是对于一个项目,它无法提取文本(在下面的代码中被称为“项目”)。我收到以下错误:“item = items.find("image:title").text AttributeError: 'NoneType' object has no attribute 'text'” 我只想获取 'item' 的文本。
这是我的代码:
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'}
url = 'https://www.kith.com/sitemap_products_1.xml'
r = requests.get(url=url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
for items in soup.find_all("url"):
item = items.find("image:title").text
url = items.find("loc").text
if item is not None:
print(item, url)
解决方案
基本上在这一行:
item = items.find("image:title").text
items.find("image:title")
返回None
(可能是因为find
在 中找不到您所期望的items
)。那么 asNone
没有该属性text
然后(None).text
引发错误AttributeError: 'NoneType' object has no attribute 'text'
如果要修复错误,可以执行以下操作:
item = items.find("image:title")
if item:
title = item.text # you can use other variable name if you want to.
else:
print("there is no image:title in items")
推荐阅读
- oracle - PLSQL 脚本不以两种不同的格式(即 .csv 和 .log)导出假脱机以获得相同的输出
- docker - GCP MIG 容器日志到 GCS 存储桶
- gitlab - 如何在浏览器上首次登录 gitLab
- ubuntu - 错误:nginx:[emerg] /etc/nginx/sites-enabled/wordpress.conf 中“return”指令中的参数数量无效
- javascript - nginx javascript模块持久化
- react-native - 当 onChangeText 已经在使用时,有没有办法用 textinput 设置状态?
- powerbi - 我可以在 pbix 中使用雪花模式吗?
- angular - 尝试以角度发布数据时出现未知错误
- javascript - Mongoose 自动改变值的类型
- python - python defaultdict如何使用它而不是函数