我正在做一个项目,有这样一个问题,我想从一个下拉列表中选择一个元素,但是找不到方法。我试过针对值的ID,但其中的问题是,ID之间的3个字母在每次加载页面时都会发生变化.而这段代码似乎并不奏效。
element = browser.find_by_id('select2-f_country-container').click()
browser.find_by_xpath('//*[@id="select2-f_country-result"]/ul/li[4]').click()
先谢谢你了。
你可以创建一个函数,将国家名称作为文本传递。
处理动态元素Induce WebDriverWait
()并等待 element_to_be_clickable
()
def selectCountry(strcountry):
browser.find_element_by_id('select2-f_country-container').click()
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//ul[@id="select2-f_country-results"]//li[text="{}"]'.format(strcountry)))).click()
selectCountry("Albania")
请注意,您需要导入以下库
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
有时元素可能不可见,如果是这样,你可以使用下面的ocde。
def selectCountry(strcountry):
browser.find_element_by_id('select2-f_country-container').click()
element=WebDriverWait(browser,10).until(EC.presence_of_element_located((By.XPATH,'//ul[@id="select2-f_country-results"]//li[text="{}"]'.format(strcountry))))
element.location_once_scrolled_into_view
element.click()
selectCountry("Albania")