📌  相关文章
📜  find_element_by_link_text() 驱动方法 – Selenium Python

📅  最后修改于: 2022-05-13 01:55:49.211000             🧑  作者: Mango

find_element_by_link_text() 驱动方法 – Selenium Python

Selenium 的Python模块是为使用Python执行自动化测试而构建的。 Selenium Python绑定提供了一个简单的 API 来使用Selenium WebDriver 编写功能/验收测试。安装selenium并签出 - 使用 get 方法导航链接后,您可能想更多地使用Selenium Python。在使用selenium (如 geeksforgeeks)打开页面后,您可能希望自动单击某些按钮或自动填写表格或任何此类自动化任务。

本文围绕如何使用Selenium Web Driver 的定位策略来抓取或定位网页中的元素。更具体地说,本文讨论了 find_element_by_link_text()。使用此策略,将返回链接文本值与位置匹配的第一个元素。如果没有元素具有匹配的链接文本属性,则会引发 NoSuchElementException。

句法 -

driver.find_element_by_link_text("Text of Link")

例子 -
例如,考虑这个页面源:

HTML

 
   
 

Are you sure you want to do this?

      Continue   Cancel


Python3
# Python program to demonstrate
# selenium
 
# import webdriver
from selenium import webdriver
 
# create webdriver object
driver = webdriver.Firefox()
 
# enter keyword to search
keyword = "geeksforgeeks"
 
# get geeksforgeeks.org
driver.get("https://www.geeksforgeeks.org/")
 
# get element
element = driver.find_element_by_link_text("Tutorials")
 
# print complete element
print(element)


现在,在您创建驱动程序后,您可以使用 -

login_form = driver.find_element_by_link_text('Continue')

如何在Selenium中使用 driver.find_element_by_link_text() 方法?

让我们尝试实际实现此方法并获取“https://www.geeksforgeeks.org/”的元素实例。让我们尝试使用其链接文本“Tutorials”来获取搜索表单输入。

创建一个名为 run.py 的文件来演示 find_element_by_link_text 方法 -

Python3

# Python program to demonstrate
# selenium
 
# import webdriver
from selenium import webdriver
 
# create webdriver object
driver = webdriver.Firefox()
 
# enter keyword to search
keyword = "geeksforgeeks"
 
# get geeksforgeeks.org
driver.get("https://www.geeksforgeeks.org/")
 
# get element
element = driver.find_element_by_link_text("Tutorials")
 
# print complete element
print(element)

现在使用 -

Python run.py

首先,它将使用 geeksforgeeks 打开 Firefox 窗口,然后选择元素并在终端上打印,如下所示。

浏览器输出 –

find_element-driver-method-Selenium-Python

终端输出 -

终端输出-find_element-method-Python-selenium

用于定位单个元素的更多定位器

LocatorsDescription
find_element_by_idThe first element with the id attribute value matching the location will be returned.
find_element_by_nameThe first element with the name attribute value matching the location will be returned.
find_element_by_xpathThe first element with the xpath syntax matching the location will be returned.
find_element_by_link_textThe first element with the link text value matching the location will be returned.
find_element_by_partial_link_textThe first element with the partial link text value matching the location will be returned.
find_element_by_tag_nameThe first element with the given tag name will be returned.
find_element_by_class_namethe first element with the matching class attribute name will be returned.
find_element_by_css_selectorThe first element with the matching CSS selector will be returned.