有谁知道这个问题从何而来?我在几秒钟内运行相同的代码,有时它会给我这个错误,有时它不会。
page = requests.get(URL, headers=headers)
soup1 = BeautifulSoup(page.content, 'html.parser')
soup2 = BeautifulSoup(soup1.prettify(), 'html.parser')
title = soup2.find(id='productTitle').get_text()
price = soup2.find(class_='aok-offscreen').get_text()
print(title)
print(price)
它确实是相同的代码,我运行它,有时它显示错误,我继续搜索元素并工作一是一否,谢谢。
---> 10 title = soup2.find(id='productTitle').get_text()
11 price = soup2.find(class_='aok-offscreen').get_text()
14 print(title)
AttributeError: 'NoneType' object has no attribute 'get_text'
问题是不存在 id 为“productTitle”的元素。您可以尝试在两个单独的命令上运行它,例如
title_elem = soup2.find(id='productTitle')
print(title_elem)
这将打印 None。因此,当您尝试访问 title_elem 上的 get_text() 方法时,就像
print(title_elem.get_text())
这会产生错误。