【问题标题】:Selenium - find id based on class tagSelenium - 根据类标签查找 id
【发布时间】:2022-01-05 21:47:44
【问题描述】:

我想用 Selenium (python) 找到一个基于 class 标签的 id

我想找到一个 html 表单的结果。有 2 个可能的结果,可用或不可用。 这两个选项都会出现在 html 代码中,但会使用两种不同的 CSS 格式来显示结果并隐藏另一个选项。

我想根据 div 类“Content Warning”(这是结果)获取 id(“WarningDisponible”或“WarningIndisponible”),“Content Warning hidden”不是结果。

非常感谢!

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    根据类名打印id属性的值,即WarningIndisponible Content warning您可以使用以下任一Locator Strategies

    • 使用css_selector

      print(driver.find_element(By.CSS_SELECTOR, "div.Content.warning > p").get_attribute("id"))
      
    • 使用xpath

      print(driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id"))
      

    理想情况下,您需要为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

    • 使用CSS_SELECTOR:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.Content.warning > p"))).get_attribute("id"))
      
    • 使用XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='Content warning']/p"))).get_attribute("id"))
      
    • 注意:您必须添加以下导入:

      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 完美运行 CSS 不起作用,因为它似乎不需要完美匹配。由于 2 个标签是“ContentWarning”或“ContentWarning Hidden”且后者始终位于顶部,因此始终将后者显示为第一个结果。无论如何,这都解决了。谢谢
    • @olivier 是的,告诉我,您需要进一步的帮助吗?
    • @Debanjay 碰巧,你知道 javascript 中的相同指令吗? selenium 的代码太慢了,我想用代码注入器在页面中注入 javascript 代码,但我有同样的问题来找到合适的标签。再次感谢
    • @olivier 很高兴能为您提供帮助。 Vote up questions and answers 您发现这对未来读者的利益很有帮助。见Why is voting important
    【解决方案2】:

    这个网站应该有帮助:https://selenium-python.readthedocs.io/locating-elements.html 先用ContentWarning = driver.find_element_by_class_name('Content Warning')搜索div 从那里您可以通过检查 ContentWarning.find_element_by_id('WarningDisponible') 是否返回任何结果来在 div 中进行搜索。

    这确实假设除了您要查找的 div 之外,HTML 中没有其他类名为“内容警告”的元素。

    【讨论】:

    • 谢谢。确实只有一个标签“内容警告”。有没有办法直接获取 id 的名称而不是测试 1 的存在(以得出结果)?
    • 尝试p_element = contentWarning.find_element_by_tag_name('p') 然后p_element.get_attribute('id')
    猜你喜欢
    • 1970-01-01
    • 2020-12-20
    • 2017-05-04
    • 2020-10-24
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多