首页 > 解决方案 > BeautifulSoup 的问题(找不到所有元素)

问题描述

我正在使用 BeautifulSoup 解析网站及其产品。我编写了一个脚本,它返回商品名称、价格和确切的 URL。

我的问题是这些行

containers = soup.find_all("div", {"class": "ProductList-grid clear"})
print(len(containers))
# Output is ALWAYS 1

http://prntscr.com/kbq9mz

如果您从屏幕截图中注意到,只有 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 新手,想尽可能地改进。

标签: pythonbeautifulsoup

解决方案


这将找到 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)

推荐阅读