尽管没有错误并假设逻辑正确,但仍获取空列表

问题描述

当我打印以下内容时,我得到一个空列表,我很确定代码是正确的

我正在尝试检索级别 0 和级别 1 的值

网站:https://stamprally.org/

prefectureValues = []
prefectureValueStorage = driver.find_elements_by_class_name(
    'div.header_search_inputs>select#header_search_cat1 > option.level-0.level-1')

for prefectureCode in prefectureValueStorage:
    prefectureValues.append(prefectureCode.get_attribute('value'))

print(prefectureValues)

Wanted List values

解决方法

//select[@name='search_cat1']/option[@class='level-1' or @class='level-0']

应该是一个简单的 xpath,用于获取这些类的所有选项。

#header_search_cat1>:is(option.level-1,option.level-0)

将是上述内容的 css 选择器。

所以把它放在一起

prefectureValues =[x.get_attribute('value') for x in driver.find_elements_by_xpath("//select[@name='search_cat1']/option[@class='level-1' or @class='level-0']")]
print(prefectureValues)

输出

['145','66','67','68','69','70','71','72','73','74','75','76','77','78','79','80','81','82','83','84','85','86','87','88','89','90','91','92','94','93','95','96','97','98','99','100','101','102','103','104','105','106','107','108','109','110','111','112','113','114','115','116','117','118','119','120']

你也可以使用等待等

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
wait=WebDriverWait(driver,10)
driver.get("https://stamprally.org/")
searchCat1Options=wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"#header_search_cat1>:is(option.level-1,option.level-0)")))
prefectureValues=[x.get_attribute('value') for x in searchCat1Options]
print(prefectureValues)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...