Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeautifulSoup出现问题(无法找到所有元素)_Python_Beautifulsoup - Fatal编程技术网

Python BeautifulSoup出现问题(无法找到所有元素)

Python BeautifulSoup出现问题(无法找到所有元素),python,beautifulsoup,Python,Beautifulsoup,我正在使用BeautifulSoup解析一个网站及其产品。我编写了一个脚本,返回商品名称、价格和准确的URL 我的问题是这些台词 containers = soup.find_all("div", {"class": "ProductList-grid clear"}) print(len(containers)) # Output is ALWAYS 1 如果您从屏幕截图中注意到,控制台上只打印了1个,而实际上应该打印4个内容: 我不确定为什么它只找到了第一个产品,而没有找到其他3个 这是

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

我的问题是这些台词

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

如果您从屏幕截图中注意到,控制台上只打印了1个,而实际上应该打印4个内容: 我不确定为什么它只找到了第一个产品,而没有找到其他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新手,希望尽可能多地改进。

您选择的是整个网格,但只有一个网格,请选择所有产品,而不是使用
ProductList item

soup.find_all("div", {"class": "ProductList-item"})

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

啊,明白了。谢谢你的帮助!