首页 > 解决方案 > 找不到特定元素。硒。Python

问题描述

自动填写表格。找不到月份选项。

此代码选择第 6 天作为日期选项。

driver.find_element_by_xpath("//option[contains(@value,'06')][1]").click()

这段代码是我认为第 12 个月的代码,但在年份部分调用 1912

driver.find_element_by_xpath("//option[contains(@value,'12')][1]").click()

链接是https://users.premierleague.com/a/profile/register/personal

在此处输入图像描述

所有 3 个答案都是可行的,我掷硬币选择接受哪个答案以避免偏见。谢谢您的帮助

标签: pythonseleniumxpath

解决方案


There are 5 elements with

//option[contains(@value,'06')][1]

so use find_elements first like this :

all_elements = driver.find_elements_by_xpath("//option[contains(@value,'06')][1]")

and then click on whichever you want :-

all_elements[0].click() #to click on first element. 

Also, full code to select date, Month, year using JS would be :

driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.get("https://users.premierleague.com/a/profile/register/personal")
driver.execute_script("return document.getElementById('ismjs-profile-dob-day').selectedIndex = '2'")
driver.execute_script("return document.getElementById('ismjs-profile-dob-month').selectedIndex = '12'")
driver.execute_script("return document.getElementById('ismjs-profile-dob-year').selectedIndex = '4'")

if you notice we are using index, so it should select 2nd-December-2018

Update 1 :

driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.get("https://users.premierleague.com/a/profile/register/personal")
wait = WebDriverWait(driver, 50)
day = Select(wait.until(EC.visibility_of_element_located((By.ID, "ismjs-profile-dob-day"))))
month = Select(wait.until(EC.visibility_of_element_located((By.ID, "ismjs-profile-dob-month"))))
year = Select(wait.until(EC.visibility_of_element_located((By.ID, "ismjs-profile-dob-year"))))
day.select_by_value('04')
month.select_by_value('12')
year.select_by_value('2020')

Imports :

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

Note that, Using JS is not recommended if the job can be done via Select class, Please see the updated 1 code.


推荐阅读