【问题标题】:How to find an element with respect to the user input using Selenium and Python?如何使用 Selenium 和 Python 查找与用户输入相关的元素?
【发布时间】:2020-09-23 02:30:11
【问题描述】:

以下是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(),但它是&lt;p&gt; 元素而不是&lt;a&gt; 元素。任何人都可以提供帮助.....

【问题讨论】:

  • 第二个对象是指

    元素吗?

  • @LoganGeorge No. 一个 div 表示一个对象,我想选择第二个代码为 23456 名称为 bcd 的对象。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

要根据用户使用Selenium 的输入定位元素,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下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

    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()

    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)))))
    
  • 注意:您必须添加以下导入:

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

【讨论】:

    【解决方案2】:

    试试下面的 xpath:

    code = '23456'
    element = driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']")
    

    【讨论】:

    • 对。然后要获得兄弟姐妹,我认为它将是 driver.find_element_by_xpath("//p[@class='code' and text()='" +code +"']/following-sibling::p")
    • @frianH 成功了!但我不是很了解 xpath 的使用。你能解释更多关于 "//p[@class='code' and text()='" +code +"']" 的内容吗?
    • @LoganGeorge 你说的兄弟是什么意思?
    • @YukChan 这只是使用AND 表达式的简单逻辑。尝试搜索类名为codep 标记,并且该标记具有文本23456
    • @YukChan 用于字符串合并。
    猜你喜欢
    • 2022-01-19
    • 2021-12-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多