python - BeautifulSoup 的问题(找不到所有元素)
问题描述
我正在使用 BeautifulSoup 解析网站及其产品。我编写了一个脚本,它返回商品名称、价格和确切的 URL。
我的问题是这些行
containers = soup.find_all("div", {"class": "ProductList-grid clear"})
print(len(containers))
# Output is ALWAYS 1
如果您从屏幕截图中注意到,只有 1 被打印到控制台,而实际上应该打印 4 件事:http: //prntscr.com/kbq6l3 我不确定为什么它只找到第一个产品而不是其他 3 .
这是我的脚本:
from bs4 import BeautifulSoup as Bs
import requests
website = "https://www.revengeofficial.com"
session = requests.session()
urls_and_prices = {}
def get_items():
response = session.get(website + "/webstore")
soup = Bs(response.text, "html.parser")
containers = soup.find_all("div", {"class": "ProductList-grid clear"})
print(len(containers))
for div in containers:
item_name = div.a["href"]
get_price(website + item_name)
def get_price(item_url):
response = session.get(item_url)
soup = Bs(response.text, "html.parser")
container = soup.find_all("section", {"class": "ProductItem-details"})
for element in container:
if element.div is not None:
name = element.h1.text
price = element.div.span.text
urls_and_prices[item_url] = price
def print_item_info():
if len(urls_and_prices) == 0:
print("Could not find any items")
return
for key, value in urls_and_prices.items():
name = key.split("/")[4]
print("Item name: " + name)
print("Price: " + value)
print("Link: " + key)
get_items()
print_item_info()
感谢您的帮助,谢谢。
编辑:另外,我很感激对我的代码的批评。我是 python 新手,想尽可能地改进。
解决方案
这将找到 4 个项目
containers = soup.find_all("a", {"class": "ProductList-item-link"})
print(len(containers))
for a in containers:
item_name = a["href"]
get_price(website + item_name)
推荐阅读
- algorithm - Scala编程中两个非负整数A和B的十进制zip是整数C
- android - 在 Android 中模拟 BuildConfig
- javascript - 检查 JSON 响应数据是否为空
- arrays - 批量循环数组的值
- python - 如何在Django中提交按钮后清除表单字段
- r - 用 ggplot2 绘制 4 组 - 女性录取和未录取,男性录取和未录取
- python - 在 when() 中使用带注释的值作为值
- python - Python,为什么使用外部函数传递和更改类自变量可用于操作迭代而不是变量
- java - ProcessBuilder - 数组参数
- php - Ubuntu 中 php 5.6 中的 Oracle 数据库连接