我不知道发生了什么,但两天前相同的代码仍在运作!
我尝试做的是使用itemprop =" name"来获取文本,这是所提供项目的标题。在这种情况下:" Swatch"。
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()
答案 0 :(得分:1)
您得到的错误告诉您页面上没有此类元素。 昨天本来可以,但网站的标记可能会改变。
您可以确保您提供条件的元素确实存在:
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')
答案 1 :(得分:1)
您获得None
的原因是因为该HTML页面中没有名为itemprop
的属性且其值设置为name
的元素。
查看源代码,肯定有使用itemprop
属性的元素,例如:
<div itemprop='description' class="description">
Batterie leer,ansonsten funktionsfähig!
</div>
<div itemprop='offers' itemscope itemtype='http://schema.org/Offer' class="container right">
但是没有像<div itemprop='name'>
那样的元素,这就是为什么你会回到None
。
@dmitriy是正确的,因为最可能的原因是网站已更新。