簡體   English   中英

如何使用 Selenium 和 Python 通過鏈接文本單擊按鈕

[英]How to click on a button by the link text using Selenium and Python

我知道,有很多針對此任務的教程。 但似乎我做錯了什么,我需要幫助告訴我如何按下它,不需要通過文字。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, 'login or register'))
    )
    element.click()
except:
    print('exception occured')
    driver.quit()

我正在嘗試從網站 wilds.io 按下“登錄或注冊”按鈕,但似乎 10 秒后找不到該按鈕。 我可能以錯誤的方式訪問按鈕。

要單擊帶有文本作為登錄或注冊的元素,您必須為element_to_be_clickable()誘導WebDriverWait ,您可以使用以下任一定位器策略

  • 使用LINK_TEXT

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "login or register"))).click()
  • 使用PARTIAL_LINK_TEXT

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "login or register"))).click()
  • 使用XPATH使用text()

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[text()='login or register']"))).click()
  • 使用XPATH使用contains()

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[contains(., 'login or register')]"))).click()
  • 注意:您必須添加以下導入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

暫無
暫無

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

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