简体   繁体   English

使用 Selenium 和 Python 定位具有动态 ID 的元素

[英]Locating an element with dynamic ID using Selenium and Python

I need to find an element by ID "start-ads", but the numbers at the end change every time.我需要通过 ID“start-ads”找到一个元素,但最后的数字每次都会改变。 Is it possible to search for an element not by the whole ID, but only by its part?是否可以不按整个 ID 搜索元素,而仅按其一部分?

Full element id: <div id="start-ads-202308">

You can use find_element_by_css_selector and use a CSS selector that matches using a prefix您可以使用find_element_by_css_selector并使用使用前缀匹配的 CSS 选择器

driver.find_element_by_css_selector("div[id^='start-ads-']")

To identify the following element:识别以下元素:

<div id="start-ads-202308">

considering the static part of the value of id attribute you can use either of the following Locator Strategies :考虑到id属性值的 static 部分,您可以使用以下任一定位器策略

  • Using css_selector :使用css_selector

     element = driver.find_element(By.CSS_SELECTOR, "div[id^='start-ads-']")

    where ^ denotes starts-with其中 ^ 表示开始于

  • Using xpath :使用xpath

     element = driver.find_element(By.XPATH, "//div[starts-with(@id, 'start-ads-')]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM