首页 > 解决方案 > Python BeautifulSoup 发现所有错误(对象没有属性)

问题描述

下面的脚本旨在浏览 ebay 搜索页面上的 ebay 列表。搜索页面只是一个列表,所以我试图遍历每个 li 标签并将内容添加到变量中。由于某种原因,这个脚本似乎不想工作,我不知道为什么。

from urllib.request import urlopen
from bs4 import BeautifulSoup

# specify the url
url = "https://www.ebay.co.uk/sch/i.html?_from=R40&_nkw=funko+gamora+199&_sacat=0&LH_Sold=1&LH_Complete=1&rt=nc&LH_PrefLoc=1&_ipg=200"

# Connect to the website and return the html to the variable ‘page’
try:
    page = urlopen(url)
except:
    print("Error opening the URL")

# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, 'html.parser')

# Take out the <div> of name and get its value
content = soup.find('ul', {"class": "srp-results srp-list clearfix"})

#print(content)

article = ''
for i in content.findAll('li'):
    article = article + ' ' +  i.text
print(article)

# Saving the scraped text
with open('scraped_text.txt', 'w') as file:
    file.write(article)

谁能看到我哪里出错了?

标签: pythonhtmlbeautifulsoup

解决方案


这是响应的样子:

print(soup.text)

安全措施跳至主要内容 请验证自己以继续错误 为了让 eBay 成为一个安全的买卖场所,我们有时会要求您验证自己。这有助于我们阻止未经授权的用户进入我们的网站。请验证自己如果您在上述验证页面上呈现图像时遇到困难,eBay 建议使用最新版本的浏览器或此处列出的备用浏览器 附加网站导航关于eBayAnnouncementsCommunitySafety CentreResolution CentreSeller CentreVeRO: Protecting Intellectual PropertyPoliciesHelp & ContactSite MapCopyright © 1995-2021 eBay Inc. 保留所有权利。用户协议、隐私、Cookie 和 AdChoiceNorton 安全 - 由 Verisign 提供支持

这是 ebay 端的错误,您的代码乍一看很好。另外,请注意,网络抓取是一个灰色区域,一些公司不允许这样做。您可能需要绕过安全措施。

此外,您应该以这样的方式评论您的代码,告诉读者为什么您的代码会执行它的功能,而不是它的功能。您不必评论诸如“soup = BeautifulSoup(page, 'html.parser')”之类的内容

编辑:我忘了提,出现错误,因为

content = soup.find('ul', {"class": "srp-results srp-list clearfix"})

没有发现任何结果。


推荐阅读