【问题标题】:soup.select returns empty list. Need help finding the source of the css codesoup.select 返回空列表。需要帮助查找 css 代码的来源
【发布时间】:2020-07-25 00:48:29
【问题描述】:

我目前正在学习“自动化无聊的东西”Udemy 课程,第 40 课。使用 Beautiful Soup 模块解析 HTML。大约几分钟后,Al 使用请求亚马逊页面的 html 并使用带有价格选择器的 soup.select 以将其打印出来。我目前正在尝试使用完全相同的代码,但似乎有必要使用标头,否则我会收到服务器错误。我已经阅读了一些类似的问题,一般的解决方案似乎是使用网络面板找到数据的来源。不幸的是,我不知道该怎么做:/

import requests
import bs4
headers = {'User-Agent': 'Chrome'}
url = 'https://www.amazon.com/Automate-Boring-Stuff-Python-Programming-ebook/dp/B00WJ049VU/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr='
res = requests.get(url, headers=headers)
soup = bs4.BeautifulSoup(res.text, features='html.parser')
print(soup.select('#mediaNoAccordion > div.a-row > div.a-column.a-span4.a-text-right.a-span-last > span.a-size-medium.a-color-price.header-price'))

【问题讨论】:

  • 您的问题需要进一步澄清,请在您的问题中添加代码示例。在我们看到您迄今为止所做的更多工作之前,我们无法为您提供帮助。
  • @AndréFradinho 你想要的输出是什么?
  • @αԋɱҽԃαмєяιcαη prntscr.com/rxsi09
  • @PatrickArtner 我收到了五个请求。我应该走“试错”路线还是有办法找到我需要的特定元素?
  • @AndréFradinho 22.86 是什么值?它没有出现在 page

标签: python python-3.x beautifulsoup


【解决方案1】:

为了更好的使用,您可以inspect element 并单击左上角的箭头图标并激活它。然后您可以将鼠标悬停在元素上并选择。选择后可以选择复制xpath/css selector/class/id

【讨论】:

    【解决方案2】:

    您需要使用更宽容的解析器。您还可以使用更短、更健壮的选择器。

    import requests
    import bs4
    
    headers = {'User-Agent': 'Chrome'}
    url = 'https://www.amazon.com/Automate-Boring-Stuff-Python-Programming-ebook/dp/B00WJ049VU/ref=tmm_kin_swatch_0?_encoding=UTF8&qid=&sr='
    res = requests.get(url, headers=headers)
    soup = bs4.BeautifulSoup(res.text, features='lxml')
    print(soup.select_one('.mediaTab_subtitle').text.strip())
    

    【讨论】:

    • 非常感谢!我只是想知道你从哪里得到“.mediaTab_subtitle”。
    • 我在页面的 html 中看到了它。我最初搜索价格是为了看看它出现在哪里。
    猜你喜欢
    • 1970-01-01
    • 2013-07-17
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多