猿问

对象没有属性“文本”

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


心有法竹
浏览 298回答 2
2回答

MMTTMM

基本上在这一行:item = items.find("image:title").text items.find("image:title")返回None(可能是因为find在 中找不到您期望的内容items)。那么因为None没有属性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")

斯蒂芬大帝

您的第一个文本返回,None因此您收到此错误。在尝试获取文本之前,您需要检查 item 是否为 none。for items in soup.find_all("url"):getTitle = items.find('image:title')if getTitle is not None:    item = getTitle.text    url = items.find("loc").text    print (item,url)
随时随地看视频慕课网APP

相关分类

Python
我要回答