簡體   English   中英

如何使用python硒單擊網頁中最后找到的文本

[英]How to click the last found text in webpage using python selenium

在網頁上,

同名文字太多

  1. 探索
  2. 探索
  3. 探索
  4. 探索
  5. 探索

我要點擊第五或第四

注意:每次重新加載網頁時,計數每次都不同

  1. 探索
  2. 探索
  3. 探索
  4. 探索
  5. 探索
  6. 探索
  7. 探索

我想單擊第六或第七文本。

請給出解決方案:

使用以下語法:不起作用driver.find_elements_by_xpath(“ // * [contains(text(),'Explore')]”)

嘗試通過CSS-選擇器選擇此元素,例如,如果“ EXPLORE”元素是一個段落:

locator = (By.CSS_SELECTOR,'p *:last-child')

# Alternative 
# locator = (By.CSS_SELECTOR,'p:last-child')

# Alternative
# locator = (By.XPATH,"//p[contains(text(),'Explore')][last()]")

def click_button(self, *locator):
   button = self.driver.find_element(*locator)
   button.click()

如果您想單擊pre-last元素:

locator = (By.CSS_SELECTOR,'p:nth-last-child(2)')

希望對您有所幫助。

您可以使用Python slice功能,獲取最后兩個Explore,如果只有一個Explore,則獲取唯一的Explore。

eles = driver.find_elements_by_xpath("//*[contains(., 'Explore')]")

for ele in eles[-2:]:
  ele.click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM