Selenium Python 无法单击下拉列表中的每个项目



我需要从本页单击下拉列表中的每个项目,我编写此代码用于单击下拉列表中的每个项目,但我在单击几个项目后得到错误element is not attached to the page document

下面是我的代码:
option_variations = driver.find_element_by_css_selector('#sid')
if option_variations:
options = [x for x in option_variations.find_elements_by_tag_name("option")]
for i in options:
variation = i.text
click_item = driver.find_element_by_xpath(f"//*[contains(text(), '{variation}')]")
click_item.click()
print(f"sucessfully click on item {variation}")
time.sleep(3)

下面的代码应该可以工作:

#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.by import By
import chromedriver_autoinstaller
from selenium.webdriver.chrome.service import Service
import time
chromedriver_autoinstaller.install()
driver = webdriver.Chrome(service=Service())
# open page
driver.get("https://www.zzounds.com/item--PGHPHM")
# get the variations into an array
elements = driver.find_elements(by=By.CSS_SELECTOR, value="#sid option")
values = []
for element in elements:
value = element.get_attribute("value")
values.append(value)
print(values)
# click on each variation
for value in values:
click_item = driver.find_element(by=By.CSS_SELECTOR, value=f"#sid option[value='{value}']")
click_item.click()
print(f"sucessfully click on item {value}")
time.sleep(1)

每个变量的xpath选择器本身的问题并不总是有效的,您必须首先为每个选项创建一个简单的字符串列表。

最新更新