[英]iterating through carousel objects in selenium with python
使用 selenium 我想在 gog.com 顶部的轮播中遍历游戏我想打印所有价格,下面是我在轮播中想要的信息的 2 个随机 xpath
/html/body/div[2]/div/div[3]/div/div[3]/div[2]/div/a[4]/div[2]/div/div/div[3]/div/span/span
/html/body/div[2]/div/div[3]/div/div[3]/div[2]/div/a[10]/div[2]/div/div/div[3]/div/span/span
这让我想遍历第一个 a 元素。 每个都是不同的游戏。 但它要么找不到那个路径,不返回任何数据,要么返回一个没有属性 .text 或 .innerhtml 的对象,这样我就无法获得我想要的信息
下面是我的脚本
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r"../Downloads/chromedriver.exe")
driver.get('https://www.gog.com/')
driver.maximize_window()
WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,"/html/body/div[2]/div/div[3]/div/div[3]/div[2]/div/a[10]/div[2]/div/div/div[3]/div/span/span")))
for i in range(15):
i+=1;
A = "/html/body/div[2]/div/div[3]/div/div[3]/div[2]/div/a["+str(i)+"]/div[2]/div/div/div[3]/div/span[2]/span"
try:
print(driver.find_elements_by_xpath(A));
print(driver.find_elements_by_xpath(A).text);
print(str(driver.find_elements_by_xpath(A)));
finally:
pass
下面是它返回的对象的示例
[<selenium.webdriver.remote.webelement.WebElement (session="3ec9e534c096a49d3110dea89fea3864", element="0bf0c6b6-fb35-4e26-8bf4-acbb7431eafb")>]
下面是它返回的错误示例
Traceback (most recent call last):
File "C:\Users\User\Desktop\mi faaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaak.py", line 16, in <module>
print(driver.find_elements_by_xpath(A).text);
AttributeError: 'list' object has no attribute 'text'
下面是我想要信息的实际元素的示例
<span class="big-spot__price-amount" ng-bind="tile.data.price.finalAmount">13.69</span>
我怎样才能让它在本页顶部的轮播中打印所有价格https://www.gog.com/
您正在为单个元素的 xpath 使用find_elements_by_xpath方法,该方法返回一个列表。 所以改用find_element_by_xpath 。
建议:与其写绝对 xpath,不如让它通用。 让你的代码看起来像这样:
carousel_xpath = '//your generic xpath here'
carousel_elements = driver.find_elements_by_xpath(carousel_xpath)
for carousel in carousel_elements:
print(carousel.text)
//do your things here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.