Я использую 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()
Я ценю помощь, спасибо.
EDIT: Кроме того, я был бы признателен за критику моего кода. Я новичок в python и хочу улучшить как можно больше.
Вы выбираете целые сетки, и есть только 1 сетка, выбирайте все продукты, выбирая с помощью 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)