問(wèn)題描述
我在 python 中使用 selenium,現(xiàn)在我想通過(guò)它的 id 名稱(chēng)的一部分來(lái)定位一個(gè)元素,我該怎么辦?
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)通過(guò) id 名稱(chēng) coption5 找到了一個(gè)項(xiàng)目:
For example,now I've already located a item by id name coption5 :
sixth_item = driver.find_element_by_id("coption5")
有沒(méi)有我只能使用 coption 來(lái)定位這個(gè)元素?
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
和 ^
(開(kāi)頭的通配符):
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)于動(dòng)態(tài) CssSelectors 的詳細(xì)討論:
You can find a detailed discussion on dynamic CssSelectors in:
- 如何使用 Selenium 和 Python 獲取內(nèi)部具有動(dòng)態(tài)部分的選擇器?
- JavaSelenium webdriver 表達(dá)式通過(guò) ccs 查找以 開(kāi)頭和結(jié)尾的動(dòng)態(tài)元素
- 如何在通過(guò) Selenium 和 Python 實(shí)現(xiàn)自動(dòng)化的同時(shí)使用 xpath/css 選擇器在 drupal 8 網(wǎng)站中單擊動(dòng)態(tài)鏈接
- 通過(guò) CSS 選擇器查找元素在 Python 中使用 ChromeDriver (Selenium)
這篇關(guān)于如何使用python在selenium中通過(guò)其id名稱(chēng)的一部分查找元素的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!