解釋一些使用 Python 在 Selenium 中建立自定義 CSS 的方法?
CSS 是 Selenium 中重要的定位器之一。可以使用 id、類名以及標籤名和 HTML 屬性的組合來開發自定義 CSS。
建立 CSS 的方法如下:
使用 class 名字 HTML 屬性。
這將選擇由 (.)classname 表示的特定類的 Web 元素。
語法:
driver. find_element_by_css_selector(".name")這裡 name 是 class 屬性的值。
使用 id HTML 屬性。
這將選擇由 (#)id 表示的特定 id 的 Web 元素。
語法:
driver. find_element_by_css_selector("#search")這裡 search 是 id 屬性的值。
使用標籤名和屬性值的組合。
這將選擇特定屬性值組合的 Web 元素。這由 tagname[attribute='value'] 表示。
語法:
driver. find_element_by_css_selector ("input[id='result']")這裡 input 是標籤名,id 屬性的值為 result。
示例
使用 class 名字屬性的 CSS 程式碼實現。
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 class name attribute
driver. find_element_by_css_selector(".gsc-input").
send_keys("Selenium")
#to close the browser
driver.close()使用 id 屬性的 CSS 程式碼實現。
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 attribute
driver. find_element_by_css_selector("#gsc-i-id1").
send_keys("Selenium")
#to close the browser
driver.close()使用標籤名和屬性值的 CSS 程式碼實現。
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 tagname and attribute value
driver. find_element_by_css_selector("input[name='search']").
send_keys("Selenium")
#to close the browser
driver.close()
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP