захват всех данных внутри div с селеном - PullRequest
1 голос
/ 27 марта 2020

Я бы хотел программно получить все названия и цены из игр в разделе топ-предложений на веб-сайте Gog.

Я выбираю раздел топ-предложений, но тогда я не уверен, как итерацию какой находится внутри этого раздела (если это возможно), чтобы найти каждого div, рекламирующего игру, и поместить имена и цены в список.

Вот что у меня так далеко. Это возможно? Как мне это сделать?

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome(executable_path=r"../Downloads/chromedriver.exe")

driver.get('https://gog.com')
wait = WebDriverWait(driver,30)
time.sleep(30); # give it a while make sure it loads
top_deals_section = driver.get_element_by_id("f0a67846-5310-11ea-ba0a-fa163eee4696")# this is the top deals section
names = []
prices = []
for div in top_deals_section:
    if div.class == 'title-product_title_title':
    names.append(div)
    ## same for prices here

где я получил 'title-product_title_title' от

Ответы [ 2 ]

0 голосов
/ 27 марта 2020

Чтобы получить все название продукта и цены в Горячие предложения . Вызовите WebDriverWait () и visibility_of_element_located (), чтобы загрузить элемент, а затем используйте приведенный ниже xpath, чтобы получить название продукта и цену.

Примечание: Некоторые элементы, не видимые на веб-странице, следовательно, используют element.get_attribute("textContent") для получения значения.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome(executable_path=r"../Downloads/chromedriver.exe")
driver.get('https://gog.com')
WebDriverWait(driver,30).until(EC.visibility_of_element_located((By.XPATH,"//div[@class='container' and contains(.,'Hot Deals')]")))
names = []
prices = []

for name,price in zip(driver.find_elements_by_xpath("//div[@class='container' and contains(.,'Hot Deals')]//div[@class='product-tile__title']"),driver.find_elements_by_xpath("//div[@class='container' and contains(.,'Hot Deals')]//span[@class='product-tile__price-discounted _price']")):
    names.append(name.get_attribute("textContent"))
    prices.append(price.get_attribute("textContent").strip())

print(names)
print(prices)

Выход :

['Nova Drift', 'Shadow Tactics: Blades of the Shogun', "Baldur's Gate: Enhanced Edition", 'Fallout: New Vegas Ultimate Edition', 'Frostpunk', 'XCOM® 2', 'Neverwinter Nights 2 Complete', 'Diablo + Hellfire', 'Stardew Valley', 'Unforeseen Incidents', 'Crypt of the NecroDancer', 'BATTLETECH - Mercenary Collection', 'Blade Runner', 'The Surge', 'The Witcher 3: Wild Hunt - Game of the Year Edition', 'SWAT 4: Gold Edition', 'The Bureau: XCOM® Declassified™', 'Styx: Master of Shadows', 'Iratus: Lord of the Dead', 'Divinity: Original Sin 2 - Definitive Edition', "Heaven's Vault", 'Dishonored: Complete Collection', 'Thronebreaker: The Witcher Tales', 'Vampire®: The Masquerade - Bloodlines™', 'Whispers of a Machine', 'Grim Dawn', 'Children of Morta', 'Through the Ages', 'Kingdom Come: Deliverance Royal Edition', 'Imperator: Rome', 'Outward', 'Crying Suns', 'Age of Wonders: Planetfall', 'GreedFall', 'Heroes of Might and Magic® 3: Complete', 'Deus Ex™ GOTY Edition']
['7.69', '8.79', '7.69', '7.49', '10.00', '8.79', '7.69', '6.59', '8.79', '10.39', '2.29', '23.79', '6.99', '6.19', '10.49', '4.00', '2.99', '5.00', '12.59', '15.00', '11.99', '21.99', '8.49', '7.69', '4.59', '4.00', '12.99', '6.19', '26.29', '23.49', '17.49', '15.59', '20.99', '29.49', '2.19', '0.69']
0 голосов
/ 27 марта 2020

Пожалуйста, обратитесь к решению ниже:

elements = WebDriverWait(driver, 20).until(
        EC.presence_of_all_elements_located((By.XPATH, "//div[contains(@class,'custom-section custom-section--triplet')]//div[contains(@class,'product-tile__title')]")))
    for product in elements:
        print product.text

Примечание: вам нужно добавить ниже импорта

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...