如何使用 Selenium 和 Python 通过 link 文本单击按钮
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 秒后找不到该按钮。我可能以错误的方式访问了按钮。
要单击文本为 登录或注册 的元素,您必须诱导 for the element_to_be_clickable()
and you can use either of the following :
使用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
我知道,有很多关于此任务的教程。但是好像我做错了什么,我需要帮助告诉我如何按下它,不需要通过文本。
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()
and you can use either of the following
使用
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