【问题标题】:Trying to use BeautifulSoup to learn python尝试使用 BeautifulSoup 学习 python
【发布时间】:2022-01-17 00:07:05
【问题描述】:

我正在尝试使用 BeautifulSoup 来抓取任何网站,只是为了学习,但在尝试时,我永远不会获得每个参数集的所有实例。附上我的代码,请告诉我我做错了什么:

import requests

url = "https://www.newegg.com/core-i7-8th-gen-intel-core-i7-8700k/p/N82E16819117827?Item=N82E16819117827"

result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")

price = doc.find_all(string="$")
print(price)

#### WHY DOES BEAUTIFULSOUP NOT RETURN ALL INSTANCES!?!?!?```

【问题讨论】:

  • 您想知道bs4 还是python?我认为“使用 BeautifulSoup 学习 Python”没有什么意义。
  • 想学python,只是在看一些youtube视频,他们用beautifulsoup在网上刮,所以我想练习一下

标签: python beautifulsoup


【解决方案1】:

根据问题中提供的 url,我可以看到带有 $ 符号的价格在 price-current 类名中可用。

所以我使用了find_all() 来获取所有价格。

使用下面的代码:

import requests
from bs4 import BeautifulSoup

url = "https://www.newegg.com/core-i7-8th-gen-intel-core-i7-8700k/p/N82E16819117827?Item=N82E16819117827"

result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")

price = doc.find_all(attrs={'class': "price-current"})
for p in price:
    print(p.text)

输出:

$399.99

$400.33
$403.09
$412.00

【讨论】:

  • 这个答案可以通过解释你做了什么以及为什么来改进。以目前的形式,它对帮助提问者学习 Python 几乎没有什么帮助。
【解决方案2】:

我不确定您所说的“每个参数集的所有实例”是什么意思。但是,您的代码块可能无法正常工作的一个原因是您忘记导入 BeautifulSoup 库。

from bs4 import BeautifulSoup

此外,抓取实时网站并不是最佳做法。我强烈推荐网站toscrape.com。对于新手来说,这是一个非常好的资源。直到今天我仍然使用它来磨练我的抓取技巧并扩展它们。

最后,BeautifulSoup 在您对 HTML 和 CSS(尤其是选择器语法)有很好的掌握时效果最好。如果你不知道这两个,无论你知道多少 Python,你都会有点挣扎。如果您不精通这些,BeautifulSoup documentation 可以让您了解如何导航 HTML 和 CSS。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    相关资源
    最近更新 更多