Python beautifulsoupselect方法返回回溯
我仍然在学习beautifulsoup模块,我在用python自动化枯燥的东西这本书中对此进行了回复我尝试了回复get amazon price脚本,但我得到了.select方法的回溯 错误“TypeError:”非类型“对象不可调用” 我找不到太多关于这个错误的信息,它被这个错误搞得一团糟 进口bs4 导入请求 header={'User-Agent':Mozilla/5.0 Windows NT 10.0;Win64;x64 AppleWebKit/537.36 KHTML,如Gecko Chrome/75.0.3770.100 Safari/537.36} def站点URL: x=requests.geturl,headers=header x、 为_状态引发_ soup=bs4.BeautifulSoupx.text,html.parser p=汤。选择“buyNewSection>a>h5>div>div.a-column.a-span8.a-text-right.a-span-last>div>span.a-size-medium.a-color-price.offer price.a-text-normal” abc=p[0].text.strip 返回abc 价格=站点的价格https://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994' 打印“价格为”+strprice 它必须返回一个包含价格的列表值,但如果您使用soup,我会遇到此错误。选择与soup相反。选择,您的代码有效,它只返回一个空列表。原因可以查看我们是否检查您正在使用的函数:Python beautifulsoupselect方法返回回溯,python,beautifulsoup,python-requests,Python,Beautifulsoup,Python Requests,我仍然在学习beautifulsoup模块,我在用python自动化枯燥的东西这本书中对此进行了回复我尝试了回复get amazon price脚本,但我得到了.select方法的回溯 错误“TypeError:”非类型“对象不可调用” 我找不到太多关于这个错误的信息,它被这个错误搞得一团糟 进口bs4 导入请求 header={'User-Agent':Mozilla/5.0 Windows NT 10.0;Win64;x64 AppleWebKit/537.36 KHTML,如Gecko C
help(soup.Select)
Out[1]:
Help on NoneType object:
class NoneType(object)
| Methods defined here:
|
| __bool__(self, /)
| self != 0
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
与之相比:
help(soup.select)
Out[2]:
Help on method select in module bs4.element:
select(selector, namespaces=None, limit=None, **kwargs) method of bs4.BeautifulSoup instance
Perform a CSS selection operation on the current element.
This uses the SoupSieve library.
:param selector: A string containing a CSS selector.
:param namespaces: A dictionary mapping namespace prefixes
used in the CSS selector to namespace URIs. By default,
Beautiful Soup will use the prefixes it encountered while
parsing the document.
:param limit: After finding this number of results, stop looking.
:param kwargs: Any extra arguments you'd like to pass in to
soupsieve.select().
话虽如此,看起来页面结构实际上与您试图获取的页面结构不同,缺少标记
买新的
$16.83
因此,这应该是可行的:
p=汤。选择“buyNewSection>h5>div>div.a-column.a-span8.a-text-right.a-span-last>div.inlineBlock-display>span.a-size-medium.a-color-price.offer price.a-text-normal”
abc=p[0].text.strip
abc
出[2]:
'$16.83'
另外,您可以考虑使用更细粒度的方法,让您更好地调试代码。例如:
buySection=soup.find'div',attrs={'id':'buyNewSection'} buySpan=buySection.find'span',attrs={'class':'a-size-medium a-color-price offer price a-text-normal'} 打印buyScan 出[1]: '$16.83'这意味着您选择的元素不再存在