解释一些使用 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.com/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.com/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.com/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