如何使用Selenium和Python根据用户输入查找元素? [英] How to find an element with respect to the user input using Selenium and Python?

查看:161
本文介绍了如何使用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.....

推荐答案

使用 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
    

  • 这篇关于如何使用Selenium和Python根据用户输入查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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