如何使用python在硒中按ID名称的一部分查找元素 [英] How to find element by part of its id name in selenium with python

查看:223
本文介绍了如何使用python在硒中按ID名称的一部分查找元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将selenium与python配合使用,现在我想按其ID名称的一部分来定位元素,我该怎么办?

I'm using selenium with python,now I want to locate an element by part of its id name,what can I do?

例如,现在我已经找到了一个ID为 coption5 的项目:

For example,now I've already located a item by id name coption5 :

sixth_item = driver.find_element_by_id("coption5")

反正我只能使用 coption 找到该元素吗?

Is there anyway I can locate this element only by using coption?

推荐答案

查找所使用的元素:

sixth_item = driver.find_element_by_id("coption5")

要仅通过使用 coption 来定位此元素,可以使用以下

To locate this element only by using coption you can use can use either of the following Locator Strategies:

  • 使用XPATHstarts-with():

sixth_item = driver.find_element_by_xpath("//*[starts-with(@id, 'coption')]")

  • 使用XPATHcontains():

    sixth_item = driver.find_element_by_xpath("//*[contains(@id, 'coption')]")
    

  • 使用CSS_SELECTOR^(开头为通配符):

  • Using CSS_SELECTOR and ^ (wildcard of starts-with):

    sixth_item = driver.find_element_by_css_selector("[id^='coption']")
    

  • 使用CSS_SELECTOR*(包含通配符):

  • Using CSS_SELECTOR and * (wildcard of contains):

    sixth_item = driver.find_element_by_css_selector("[id*='coption']")
    

  • 您可以在以下位置找到有关动态CssSelectors的详细讨论:

    You can find a detailed discussion on dynamic CssSelectors in:

    这篇关于如何使用python在硒中按ID名称的一部分查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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