如何使用 selenium chromewebdriver/python 在下拉内容中选择/单击 [英] How to select/click in a dropdown content using selenium chromewebdriver / python

查看:36
本文介绍了如何使用 selenium chromewebdriver/python 在下拉内容中选择/单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站表单已更新,我的脚本不再有效.我无法修复它,因为我无法找到如何使用 selenium chrome web 驱动程序和 python 在下拉内容中进行选择.

My website form have updated and my script is no more working. I cannot fix it because I'm not able to find how to select in a dropdown content using selenium chrome web driver and python.

formattedstate 是格式化数据的值(从文件中读取)

formattedstate is the value of a formatted data (read from a file)

driver.find_element_by_css_selector(f"option[title='{formattedState}']").click()

driver.find_element_by_xpath("//*[text()='{formattedState}']").click()

driver.find_element_by_css_selector(f"option[value='{formattedState}']").click()

这是来自网络表单的下拉内容的数据.我在下拉列表中选择了第一个州 = Alabama

This is the data of the dropdown content from the webform. I selected the first state in the dropdown = Alabama

<input aria-valuetext="" role="combobox" tabindex="0" 
placeholder="State/Province/Region" readonly="" height="100%" size="1" autocomplete="off" value="" data-spm-anchor-id="a2g0o.placeorder.0.i14.5f0b321eC7zfLx">



<li class="next-menu-item" title="Alabama" data-spm-anchor-id="a2g0o.placeorder.0.i17.5f0b321eC7zfLx">Alabama</li>

它应该在下拉内容中选择正确的状态

It should select the correct state in the dropdown content

推荐答案

首先尝试点击组合框,然后 等待直到状态选项(li)元素可见并点击.

First try to click to the combobox, then wait until state option(li) element is visible and click.

在下面的代码中,我使用css选择器通过title获取li.如果要按文本查找元素,请使用:
wait.until(ec.visibility_of_element_located((By.XPATH, f"//li[.='{state}' and @class = 'next-menu-item']"))).click()

In code below, I used css selector to get li by title. If you want to find element by text, use:
wait.until(ec.visibility_of_element_located((By.XPATH, f"//li[.='{state}' and @class = 'next-menu-item']"))).click()

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

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

state = "Alabama"
driver.find_element_by_css_selector('input[placeholder="State/Province/Region"]').click()
wait.until(ec.visibility_of_element_located((
    By.CSS_SELECTOR, f"li.next-menu-item[title='{state}']"))).click()

这篇关于如何使用 selenium chromewebdriver/python 在下拉内容中选择/单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆