首页 > 解决方案 > 对象没有属性“文本”

问题描述

好的,让我们再试一次。我正在抓取一个 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)

标签: pythonxmlbeautifulsoup

解决方案


基本上在这一行:

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")

推荐阅读