列出使用 Python 的 Selenium 中的不同定位器。
下面列出了在 Python 中使用 Selenium 的不同定位器。
Id - 透過元素的 id 屬性識別元素。如果找不到匹配 id 的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_id("id")Name - 透過元素的 name 屬性識別元素。如果找不到匹配 name 的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_name("name")Xpath - 透過屬性和標籤名識別元素。XPath 有兩種型別:絕對路徑和相對路徑。
語法 -
driver.find_element_by_xpath("//input[@type='type']")CSS - 透過使用 id、class 和 tagName 等屬性構建的 CSS 表示式識別元素。如果找不到匹配 CSS 的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_css_selector("#id")
Link Text - 透過包含在錨標籤中的連結文字識別元素。如果找不到匹配連結文字的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_link_text("Home Link")Partial Link Text - 透過部分匹配包含在錨標籤中的連結文字識別元素。如果找不到匹配部分連結文字的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_partial_link_text("Home")Tagname – 透過標籤名識別元素。如果元素沒有匹配的標籤名,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_tag_name("a")Class name - 透過類屬性的名稱識別元素。如果找不到匹配類名稱屬性的元素,則會引發 NoSuchElementException。
語法 -
driver.find_element_by_class_name("search")
示例
使用 id 定位器的程式碼實現。
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://tutorialspoint.tw/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of id
driver.find_element_by_id("gsc-i-id1").send_keys("Selenium")
#to close the browser
driver.close()
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP