[英]Can't locate certain element. Selenium. 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 個答案都是可行的,我擲硬幣到 select 接受這個答案以避免偏見。 謝謝您的幫助
有5個元素
//option[contains(@value,'06')][1]
所以首先像這樣使用find_elements
:
all_elements = driver.find_elements_by_xpath("//option[contains(@value,'06')][1]")
然后單擊您想要的任何一個:-
all_elements[0].click() #to click on first element.
此外,使用 JS 的 select 日期、月份、年份的完整代碼為:
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'")
如果您注意到我們正在使用索引,那么它應該是 select 2nd-December-2018
更新 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')
進口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
請注意,如果可以通過 Select class 完成工作,則不建議使用 JS,請參閱更新的 1 代碼。
該頁面上有幾個下拉菜單,每個下拉菜單包含多個選項。
對於 select 月份選項,您可以像這樣使用 XPath:
//select[contains(@id,'month')]//option[contains(@value,'12')]
到select天你可以用類似的
//select[contains(@id,'day')]//option[contains(@value,'12')]
ETC。
有很多方法可以完成此任務,但這是迄今為止針對此問題最可定制的方法。
要找到日期:
driver.find_element_by_xpath("//select[@id='ismjs-profile-dob-day']/option[text()='6']").click()
要找到月份:
driver.find_element_by_xpath("//select[@id='ismjs-profile-dob-month']/option[value()='December']").click()
要找到年份:
driver.find_element_by_xpath("//select[@id='ismjs-profile-dob-year']/option[text()='2015']").click()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.