如何使用Selenium和Python根据用户输入查找元素?
以下是HTML结构:
<div class='list'>
<div>
<p class='code'>12345</p>
<p class='name'>abc</p>
</div>
<div>
<p class='code'>23456</p>
<p class='name'>bcd</p>
</div>
</div>
并且有一个config.py供用户输入.如果用户在config.code中输入23456,Selenium python如何选择第二个对象?我正在使用find_by_css_selector()
定位并选择对象,但是它只能选择第一个对象,即 Code ='12345'.我尝试使用find_by_link_text()
,但这是一个<p>
元素,而不是<a>
元素.任何人都可以帮助.....
And there is a config.py for user input. If the user input 23456 to config.code, how can the selenium python select the second object? I am using find_by_css_selector()
to locate and select the object, but it can only select the first object, which is Code='12345'. I tried to use find_by_link_text()
, but it is a <p>
element not <a>
element. Anyone can help.....
使用 python ,您需要诱使 WebDriverWait 用于visibility_of_element_located()
,则可以使用以下任一定位器策略:
To locate the element with respect to the input by the user using Selenium and python you need to to induce WebDriverWait for the visibility_of_element_located()
and you can use either of the following Locator Strategies:
-
在
XPATH
中使用变量:
user_input = '23456'
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='" +user_input+ "']")))
在XPATH
中使用%s
:
Using %s
in XPATH
:
user_input = '23456'
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='%s']"% str(user_input))))
在XPATH
中使用format()
:
Using format()
in XPATH
:
user_input = '23456'
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='list']//div/p[@class='code' and text()='{}']".format(str(user_input)))))
注意:您必须添加以下导入:
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC