如何在 Python 中使用 Selenium 点击链接?
我们可以借助 Selenium 提供的定位器在页面上点击链接。链接文本和部分链接文本是通常用于点击链接的定位器。这两个定位器都使用锚标记内的文本。
-
链接文本:在 Selenium 中,链接文本用于网页上的超链接,要在网页上创建超链接,我们可以使用锚标记后跟链接文本。
-
部分链接文本:只有当添加了部分单词时,我们才能使用部分链接文本,这使得用户可以更快地检索。
安装 Selenium
使用以下命令在你的 Python 环境中安装 Selenium。
pip install selenium
下载 WebDriver
我们需要一个与浏览器匹配的 web 驱动程序,如果你使用的是 Chrome 浏览器,请下载 ChromeDriver 并确保将 WebDriver 可执行文件添加到系统的 PATH 中。
初始化 WebDriver
使用以下代码,我们可以导入所需的模块并初始化 webdriver。将示例路径 '/path/to/chromedriver' 替换为你系统上 ChromeDriver 可执行文件的实际路径。
from selenium import webdriver # Initializing WebDriver driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
打开网页
使用 'get' 方法,我们可以导航到包含你想要点击的链接的网页。将 'https://www.Example.com' 替换为你的链接所在的页面的 URL。
# Open the webpage
driver.get('https://www.Example.com')
使用链接文本点击链接
利用 Selenium 中提供的定位器,我们可以使用其文本、ID、名称、类、CSS 选择器或 XPath 来定位链接。链接文本定位器用于通过匹配锚标记内完全可见的文本定位链接。
driver.find_element_by_link_text("Link Text").click()
示例
在下面的示例代码中,driver.maximize_window() 函数最大化浏览器窗口。find_element_by_link_text("Company") 函数将使用其精确文本查找页面上的超链接。
from selenium import webdriver
# Browser exposes an executable file
# Through Selenium test we will invoke the executable file which will then #invoke #actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# To maximize the browser window
driver.maximize_window()
# Get method to launch the URL
driver.get("https://www.Example.com")
# To refresh the browser
driver.refresh()
# Identifying the link with the help of link text locator
driver.find_element_by_link_text("Company").click()
# To close the browser
driver.close()
使用部分链接文本点击链接
部分链接文本定位器匹配任何在锚标记内部分包含指定文本字符串的链接。
driver.find_element_by_partial_link_text("Partial Link Text").click()NoSuchElementException shall be thrown for both these locators if there is no matching element.
如果不存在匹配的元素,则这两个定位器都会抛出 NoSuchElementException。
示例
在下面的示例代码中,find_element_by_partial_link_text("Privacy") 函数查找文本包含单词 "Privacy" 的链接,并且不需要匹配链接的全文。
from selenium import webdriver
# Browser exposes an executable file
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# To maximize the browser window
driver.maximize_window()
# Get method to launch the URL
driver.get("https://tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# Identifying the link with the help of partial link text locator
driver.find_element_by_partial_link_text("Privacy").click()
# To close the browser
driver.quit()
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP