当我使用用户名mercury和PW:mercury,点击提交按钮,我进入登录成功页面。然后我需要点击左侧的主页按钮,但我不能。
from telnetlib import EC
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
driver = webdriver.Chrome(executable_path="D:ChromeDriverExtractedchromedriver")
driver.get("http://demo.guru99.com/test/newtours/")
driver.maximize_window()
driver.find_element_by_name("userName").send_keys("mercury")
driver.find_element_by_name("password").send_keys("mercury")
driver.find_element_by_name("submit").click()
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td[2]/font/a"))).click()
这是一个绝对的xpath
/html/body/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td[2]/font/a
请使用下面的一个基于文本的定位器:
//a[text()='Home']
或者像这样使用LINK_TEXT
:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Home"))).click()
您也可以使用以下CSS选择器:
a[href='index.php']
还有其他点击方式,
代码试用1:
time.sleep(5)
driver.find_element_by_xpath("//a[text()='Home']").click()
代码试用2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Home']"))).click()
代码试用3:
time.sleep(5)
button = driver.find_element_by_xpath("//a[text()='Home']")
driver.execute_script("arguments[0].click();", button)
代码试用4:
time.sleep(5)
button = driver.find_element_by_xpath("//a[text()='Home']")
ActionChains(driver).move_to_element(button).click().perform()
进口:
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.webdriver.common.action_chains import ActionChains
要点击文本为主页的元素,您需要诱导WebDriverWait等待元素_To_be_clickle((,然后您可以使用以下定位器策略之一:
-
使用LINK_TEXT:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.LINK_TEXT, "Home"))).click()
-
使用CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.signin-btn.sbLoginBtn > span.btf-text"))).click()
-
使用XPATH:
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//a[text()='Home']"))).click()
-
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC