Python Selenium 中通过标题查找并点击元素。

seleniumautomation testingtesting tools更新于 2026/1/8 5:07:17

我们可以在 Selenium webdriver 中通过标题查找并点击元素。元素可以通过 xpath 或 css 选择器通过 title 属性进行标识。使用 xpath 时,表达式应为 //tagname[@title='value']。在 CSS 中,表达式应为 tagname[title='value']。

让我们以一个带有 title 属性的元素的 HTML 代码为例。

用于识别元素的 XPath 应为 //a[@title='Tutorialspoint'],CSS 表达式应为 a[title='Tutorialspoint']。 识别元素后,我们就可以使用 click() 方法点击它了。

示例

代码实现。

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# 隐式等待 5 秒
driver.implicitly_wait(5)
# 使用 maximize_window() 最大化
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
# 使用 title 属性识别元素并点击 ()
l=driver.find_element_by_xpath("//a[@title='Tutorialspoint']")
l.click()
print("Current page title: " + driver.title)
driver.quit()

相关文章