无法将元素<option>滚动到vi中

2024-05-16 23:26:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用硒来选择一个值。

这是目标HTML:

  <div class="main_table">
        <div class="fields filter_center clearfix" style="margin: 0 auto;">
            <div class="form-group clearfix">                    
                <div class="col-sm-8">
                    <select class="form-control input-sm js-example-basic-single" name="city">
                                                            <option style="padding: 3px;" value="213">New York</option>
                                                            <option style="padding: 3px;" value="2">Washington</option>
                                                            <option style="padding: 3px;" value="47">Los Angeles</option>

我的第一次尝试:

from selenium.webdriver.support.wait import WebDriverWait


region_element = Select(drv.find_element_by_tag_name("select"))
region_element.select_by_value("2")

这会引起:

selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view

我的尝试2:

region_element = WebDriverWait(drv, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='city']")))
region_element = Select(region_element)
region_element.select_by_value("2")

再次:

selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view

尝试3(等待可单击特定选项):

region_element = WebDriverWait(drv, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='city']")))

WebDriverWait(drv, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//select[@name='city']/option[text()='Washington']")))

region_element = Select(region_element)
region_element.select_by_value("2")

再次:

selenium.common.exceptions.ElementNotInteractableException: Message: Element <option> could not be scrolled into view

你能帮我纠正这种情况吗?


Tags: namedivcitybyvaluestyleseleniumelement
1条回答
网友
1楼 · 发布于 2024-05-16 23:26:21

如果选项菜单没有隐藏在包装器中,例如另一个下拉菜单或嵌套页面尝试将操作移动到它。

element = driver.find_element_by_xpath("//select[@name='city']")

actions = ActionChains(driver)
actions.move_to_element(element).perform()

或者使用javascript执行器

driver.execute_script("arguments[0].scrollIntoView();", element)

相关问题 更多 >