python(美丽)仅1个结果
我知道与这个回答的问题相似,我已经尝试申请并没有解决我的问题。
我的问题是在此网站上: http://books.toscrape.com/catalogue/catalogue/ Page-1.html 有20个价格,当我尝试刮擦价格时,我只能获得第一个价格,但没有其他19个。
这是代码
from bs4 import BeautifulSoup
import requests
URL = 'http://books.toscrape.com/catalogue/page-1.html'
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find_all("div", class_ = "col-sm-8 col-md-9")
for i in results :
prices = i.find("p", class_ = "price_color")
print(prices.text.strip())
print()
I know there are similar questions to this one that are answered which I already tried applying and didn't fix my problem.
My problem is that on this website: http://books.toscrape.com/catalogue/page-1.html there are 20 prices and when I try to scrape the prices, I only get the first price but not other 19.
Here's the code
from bs4 import BeautifulSoup
import requests
URL = 'http://books.toscrape.com/catalogue/page-1.html'
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find_all("div", class_ = "col-sm-8 col-md-9")
for i in results :
prices = i.find("p", class_ = "price_color")
print(prices.text.strip())
print()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您以错误的方式搜索项目。
只有一个
div
,带有col-sm-8 col-md-9
,带有许多价格
,但您的代码期望许多divs
divs
/code>在每个div
中都有单个价格 - 这使问题。使用
find()
您在此div
中搜索单个价格,但是您应该使用find_all
在此单个div
中获取所有价格代码>。您甚至可以直接搜索价格
最少的工作示例:
使用
find()
才能在搜索价格上使用,只有在您首先找到单个价格的所有区域 - 例如Artical
)。每本书都在分开的
文章
中 - 因此,有许多文章
,每个文章
都有单个价格(以及单个标题,单个图像等)结果:
You search items in wrong way.
There is only one
div
withcol-sm-8 col-md-9
with manyprices
but your code expects manydivs
with single price in everydiv
- and this makes problem.Using
find()
you search single price in thisdiv
but you should usefind_all
to get all prices in this singlediv
.You could even search directly prices
Minimal working example:
Using
find()
to search price could work only if you would first find all regions with single price - likearticle
.Every book is in separated
article
- so there are manyarticles
and everyarticle
has single price (and single title, single image, etc.)Result:
此代码应该起作用!
我只是使用了Chorme选择器
的屏幕截图
这是它 代码> find_all 在错误的地方。
this code should work!
i just used chorme selector
this is a screenshot of it
you are using the
find
andfind_all
in the wrong places.班级错误。
@ihonestlydontknow,如果将此行更改为“文章”,您的代码将有效:(
正如他的答复中提到的furas)
** print(结果)(或使用 https://codebeautify.org/htmlviewer 用于检查结构。)
....
****输出
£51.77
£53.74
£50.10
£47.82
54.23英镑
£22.65
33.34英镑
£17.93
...
(vwebtuan)tng@rack-dff0:〜$ cat a.py
(vwebtuan)tng@rack-dff0:〜$
Wrong class.
@ihonestlydontKnow, if you change this line to "article", your code will work:
(as furas mentioned in his reply)
**print(results) (or using https://codebeautify.org/htmlviewer for checking the structure.)
....
****output
£51.77
£53.74
£50.10
£47.82
£54.23
£22.65
£33.34
£17.93
...
(vwebtuan) tng@rack-dff0:~$ cat a.py
(vwebtuan) tng@rack-dff0:~$