使用 Splinter lib (Python) 选择下拉菜单中的一个项目。

问题描述 投票:0回答:1

我正在做一个项目,有这样一个问题,我想从一个下拉列表中选择一个元素,但是找不到方法。我试过针对值的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()

先谢谢你了。

容器。https:/imgur.comRrQVYfR

容器代码。https:/imgur.comlSthuDd

列表代码。https:/imgur.com8KEnAC8

python selenium selenium-webdriver splinter
1个回答
0
投票

你可以创建一个函数,将国家名称作为文本传递。

处理动态元素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")
© www.soinside.com 2019 - 2024. All rights reserved.