BeautifulSoup AttributeError:“get_text”有时在同一代码中

问题描述 投票:0回答:1

有谁知道这个问题从何而来?我在几秒钟内运行相同的代码,有时它会给我这个错误,有时error它不会。

    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)

它确实是相同的代码,我运行它,有时它显示错误,works我继续搜索元素并工作一是一否,谢谢。

---> 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'
beautifulsoup python-requests python-requests-html
1个回答
0
投票

问题是不存在 id 为“productTitle”的元素。您可以尝试在两个单独的命令上运行它,例如

title_elem = soup2.find(id='productTitle')
print(title_elem)

这将打印 None。因此,当您尝试访问 title_elem 上的 get_text() 方法时,就像

print(title_elem.get_text())

这会产生错误。

© www.soinside.com 2019 - 2024. All rights reserved.