尽管没有错误并假设逻辑正确,但得到一个空列表

Get an empty List despite no error and assuming the logic is correct

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

我正在尝试检索 class level-0 和 level-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)

//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)