gpt4 book ai didi

python - 从 html 获取文本时出现属性错误

转载 作者:行者123 更新时间:2023-12-01 02:51:18 25 4
gpt4 key购买 nike

我不知道发生了什么,但两天前同样的代码仍然有效!

我尝试做的是获取 itemprop = "name"的文本,这是所提供元素的标题。在本例中:“斯沃琪”。

import requests
import bs4
response2 = requests.get('https://www.willhaben.at/iad/kaufen-und-verkaufen/d/swatch-209522646/').content

soup2 = bs4.BeautifulSoup(response2, "lxml")

texttitle = soup2.find(itemprop = "name").get_text().strip()
print(texttitle)

我怎么总是得到AttributeError: 'NoneType' object has no attribute 'get_text'谁能解释一下为什么我会收到 AttributeError ?非常感谢。

编辑:

我也尝试直接使用 css 路径找到它,但这没有给我任何结果。作者:

texttitle = soup2.find('div.adHeadingLine div.adHeading h1.header.cXenseParse').get_text().strip()

最佳答案

您收到的错误表明页面上没有这样的元素。昨天可能是这样,但网站的标记可能会改变。

您可以确保您为其指定条件的元素确实存在:

from bs4 import BeautifulSoup
from urllib2 import urlopen

response = urlopen('https://www.willhaben.at/iad/kaufen-und-verkaufen/d/swatch-209522646/')
soup = BeautifulSoup(response, "lxml")

if soup.find(itemprop='name'):
texttitle = soup.find(itemprop='name').text.strip()
print(texttitle)
else:
print('no such element')

关于python - 从 html 获取文本时出现属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44738182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com