【问题标题】:Python bs4 BeautifulSoup: findall gives empty bracketPython bs4 BeautifulSoup:findall给出空括号
【发布时间】:2017-09-04 21:12:30
【问题描述】:

当我运行这段代码时,它给了我一个空括号。我是网络抓取的新手,所以我不知道我做错了什么。

import requests

from bs4 import BeautifulSoup

url = 'https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=laptop'

r = requests.get(url)

soup = BeautifulSoup(r.text, 'html.parser')

container = soup.findAll('li', {'class': 's-result-item celwidget '})
#btw the space is also there in the html code

print(container)

结果:

[]

我尝试的是从站点获取 html 代码,并通过存储所有信息的 li 标记进行汤底,这样我就可以在 for 循环中打印出所有信息。

另外,如果有人想解释如何使用 BeautifulSoup,我们可以随时讨论。 谢谢各位。

【问题讨论】:

  • 我用你的代码得到了 16 件商品。
  • 上面的代码少了一个逗号。请正确复制粘贴。
  • 还是一无所获
  • 也许你得到了一个不好的回应。你能打印r.text和r.status_code吗?
  • @t.m.adam 是的可以

标签: python beautifulsoup bs4 findall


【解决方案1】:

因此,获取产品和价格的工作代码可能看起来像这样。

import requests
from bs4 import BeautifulSoup

url = 'https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=laptop'
r = requests.get(url, headers={'User-Agent': 'Mozilla Firefox'})
soup = BeautifulSoup(r.text, 'html.parser')
container = soup.findAll('li', {'class': 's-result-item celwidget '})
for cont in container:
    h2 = cont.h2.text.strip()

    # Amazon lists prices in two ways. If one fails, use the other
    try:
        currency = cont.find('sup', {'class': 'sx-price-currency'}).text.strip()
        price = currency + cont.find('span', {'class': 'sx-price-whole'}).text.strip()
    except:
        price = cont.find('span', {'class': 'a-size-base a-color-base'})
    print('Product: {}, Price: {}'.format(h2, price))

如果这对您有进一步帮助,请告诉我...

【讨论】:

  • 我还有一个问题,假设您有 4 个 div,其中一个 class="a" 第二个 class="b" 等等,我该如何选择我想在哪一个上做汤。我需要做这样的事情吗? soup.find('div', {'class': 'c'}).otherpath 其他路径代表它后面的内容?
  • 您从完整的汤中创建了一个新对象。 small_soup = soup.find('div', {'class': 'a'})。阅读文档。它们很广泛。
  • 所以我可以做 soup.find('div', {'class': "a"}).div.div.find('div', {'class': 'f'} )。细绳?还是这段代码返回错误?
  • 如果站点具有可能有效的结构。但在那种情况下,你最好直接用 f 类调用 div...
  • 因为我想抓取有关笔记本电脑的信息并打印出来,但我想在容器中的 for i 之类的路径中进行操作:i.div.find('div' {'class': ' b'}).etc
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2013-10-27
  • 2017-05-02
  • 2018-12-28
  • 2017-02-17
相关资源
最近更新 更多