如何使用python在selenium中通过部分id名称查找元素 [英] How to find element by part of its id name in selenium with python
问题描述
我在 python 中使用 selenium,现在我想通过元素的 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:
使用
XPATH
和starts-with()
:
sixth_item = driver.find_element_by_xpath("//*[starts-with(@id, 'coption')]")
使用 XPATH
和 contains()
:
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']")
您可以在以下位置找到关于动态 CssSelector 的详细讨论:
You can find a detailed discussion on dynamic CssSelectors in:
- 如何使用 Selenium 和 Python 获取带有动态部分的选择器?
- JavaSelenium webdriver表达式通过以 开头和结尾的ccs查找动态元素
- 如何在通过 Selenium 和 Python 自动化的同时使用 xpath/css 选择器在 drupal 8 网站中单击动态链接
- 通过 CSS 选择器查找元素使用 Python 中的 ChromeDriver (Selenium)
这篇关于如何使用python在selenium中通过部分id名称查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!