問題描述
我在 python 中使用 selenium,現(xiàn)在我想通過它的 id 名稱的一部分來定位一個元素,我該怎么辦?
I'm using selenium with python,now I want to locate an element by part of its id name,what can I do?
例如,現(xiàn)在我已經(jīng)通過 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']")
您可以在以下位置找到關(guān)于動態(tài) CssSelectors 的詳細(xì)討論:
You can find a detailed discussion on dynamic CssSelectors in:
- 如何使用 Selenium 和 Python 獲取內(nèi)部具有動態(tài)部分的選擇器?
- JavaSelenium webdriver 表達(dá)式通過 ccs 查找以 開頭和結(jié)尾的動態(tài)元素
- 如何在通過 Selenium 和 Python 實現(xiàn)自動化的同時使用 xpath/css 選擇器在 drupal 8 網(wǎng)站中單擊動態(tài)鏈接
- 通過 CSS 選擇器查找元素在 Python 中使用 ChromeDriver (Selenium)
這篇關(guān)于如何使用python在selenium中通過其id名稱的一部分查找元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!