Learning Selenium WebDriver

本文介绍如何通过注入Sizzle引擎来解决从Selenium 1过渡到Selenium WebDriver时遇到的定位问题,特别是针对CSS标准的变化导致的:contains('text')无法定位网页元素的情况。通过实现SizzleSelector类并使用其findElementBySizzleCss()和findElementsBySizzleCss()方法,可以充分利用Sizzle选择器的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Inject the Sizzle CSS selector library

Problem

We might experience some locator issues during the transition from Selenium 1 to Selenium WebDriver. We face these issues because Selenium WebDriver stays strict to the CSS standard. It might that :contains(‘text’) does not locate the web page elements anymore. The solution is to inject the Sizzle engine into the browser under test. We can make a SizzleSelector class and use the power of Sizzleselector where necessary. Shannon Code came up with a very nice class, which can be found here: http://www.prototypic.net/weblog/?p=14

Solution

This is the code of the SizzleSelector class. It injects the Sizzle engine into the browser under test by JavaScript.


import java.util.List;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
@SuppressWarnings("unchecked")
public class SizzleSelector {
private JavascriptExecutor driver;
public SizzleSelector(WebDriver webDriver) {
driver = (JavascriptExecutor) webDriver;
}
public WebElement findElementBySizzleCss(String using) {
injectSizzleIfNeeded();
String javascriptExpression = createSizzleSelectorExpression(using);
List<WebElement> elements = (List<WebElement>) driver
.executeScript(javascriptExpression);
if (elements.size() > 0)
return (WebElement) elements.get(0);
return null;
}
public List<WebElement> findElementsBySizzleCss(String using) {
injectSizzleIfNeeded();
String javascriptExpression = createSizzleSelectorExpression(using);
return (List<WebElement>) driver.executeScript(javascriptExpression);
}
private String createSizzleSelectorExpression(String using) {
return "return Sizzle(\"" + using + "\")";
}
private void injectSizzleIfNeeded() {
if (!sizzleLoaded())
injectSizzle();
}
public Boolean sizzleLoaded() {
Boolean loaded;
try {
loaded = (Boolean) driver.executeScript("return Sizzle()!=null");
} catch (WebDriverException e) {
loaded = false;
}
return loaded;
}
public void injectSizzle() {
driver.executeScript(" var headID = document.getElementsByTagName(\"head\")[0];"
+ "var newScript = document.createElement('script');"
+ "newScript.type = 'text/javascript';"
+ "newScript.src = 'https://raw.github.com/jquery/sizzle/master/sizzle.js';"
+ "headID.appendChild(newScript);");
}
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.List;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
@SuppressWarnings("unchecked")
public class SizzleSelector {
private JavascriptExecutor driver;
public SizzleSelector(WebDriver webDriver) {
driver = (JavascriptExecutor) webDriver;
}
public WebElement findElementBySizzleCss(String using) {
injectSizzleIfNeeded();
String javascriptExpression = createSizzleSelectorExpression(using);
List<WebElement> elements = (List<WebElement>) driver
.executeScript(javascriptExpression);
if (elements.size() > 0)
return (WebElement) elements.get(0);
return null;
}
public List<WebElement> findElementsBySizzleCss(String using) {
injectSizzleIfNeeded();
String javascriptExpression = createSizzleSelectorExpression(using);
return (List<WebElement>) driver.executeScript(javascriptExpression);
}
private String createSizzleSelectorExpression(String using) {
return "return Sizzle(\"" + using + "\")";
}
private void injectSizzleIfNeeded() {
if (!sizzleLoaded())
injectSizzle();
}
public Boolean sizzleLoaded() {
Boolean loaded;
try {
loaded = (Boolean) driver.executeScript("return Sizzle()!=null");
} catch (WebDriverException e) {
loaded = false;
}
return loaded;
}
public void injectSizzle() {
driver.executeScript(" var headID = document.getElementsByTagName(\"head\")[0];"
+ "var newScript = document.createElement('script');"
+ "newScript.type = 'text/javascript';"
+ "newScript.src = 'https://raw.github.com/jquery/sizzle/master/sizzle.js';"
+ "headID.appendChild(newScript);");
}
}

How to use it

The class described above will inject the Sizzle engine into the browser under test. This allows us to use all the Sizzle selector features, such as :contains(‘text’). Other classes can extended this class and we are able to use the findElementBySizzleCss() method to locate the elements.


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SizzleExample {
private static WebDriver driver;
SizzleSelector sizzle;
@BeforeClass
public void setUp() {
driver = new FirefoxDriver();
sizzle = new SizzleSelector(driver);
driver.get("http://selenium.polteq.com/prestashop/");
}
@AfterClass
public void tearDown() {
driver.close();
driver.quit();
}
@Test
public void useSizzleSelector() {
sizzle.findElementBySizzleCss("input#search_query_top").sendKeys("ipod nano");
sizzle.findElementBySizzleCss("input[name='submit_search']").click();
String searchHeader =  sizzle.findElementBySizzleCss("H1").getText().toLowerCase();
Assert.assertTrue(searchHeader.contains("ipod nano"));
}
}
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SizzleExample {
private static WebDriver driver;
SizzleSelector sizzle;
@BeforeClass
public void setUp() {
driver = new FirefoxDriver();
sizzle = new SizzleSelector(driver);
driver.get("http://selenium.polteq.com/prestashop/");
}
@AfterClass
public void tearDown() {
driver.close();
driver.quit();
}
@Test
public void useSizzleSelector() {
sizzle.findElementBySizzleCss("input#search_query_top").sendKeys("ipod nano");
sizzle.findElementBySizzleCss("input[name='submit_search']").click();
String searchHeader =  sizzle.findElementBySizzleCss("H1").getText().toLowerCase();
Assert.assertTrue(searchHeader.contains("ipod nano"));
}
}
This entry was posted in Tips & Tricks on February 4, 2012 by Roy de Kleijn.




原文地址:http://selenium.polteq.com/injecting-the-sizzle-css-selector-library/

基于C#开发的一个稳定可靠的上位机系统,旨在满足工业控制的需求。该系统集成了多个功能界面,如操作界面、监控界面、工艺流显示界面、工艺表界面、工艺编辑界面、曲线界面和异常报警界面。每个界面都经过精心设计,以提高用户体验和工作效率。例如,操作界面和监控界面对触摸屏友好,支持常规点击和数字输入框;工艺流显示界面能够实时展示工艺步骤并变换颜色;工艺表界面支持Excel和加密文件的导入导出;工艺编辑界面采用树形编辑方式;曲线界面可展示八组曲线并自定义纵坐标数值;异常报警界面能够在工艺流程出现问题时及时报警。此外,该系统还支持与倍福TC2、TC3和西门子PLC1200/300等下位机设备的通信,确保生产线的顺畅运行。系统参考欧洲工艺软件开发,已稳定运行多年,证明了其可靠性和稳定性。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是对C#编程有一定基础的人群。 使用场景及目标:适用于需要构建高效、稳定的工业控制系统的企业和个人开发者。主要目标是提升生产效率、确保生产安全、优化工艺流程管理和实现数据的有效管理与传输。 其他说明:文中提供了部分示例代码片段,帮助读者更好地理解具体实现方法。系统的复杂度较高,但凭借C#的强大功能和开发团队的经验,确保了系统的稳定性和可靠性。
from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() # 设置远程调试端口号为9222 options.add_argument("--remote-debugging-port=9222") # 必须与debuggerAddress端口一致 options.debugger_address = "127.0.0.1:9222" # 显式指定连接地址 options.add_argument("--user-data-dir=C:/Users/fzh13/Desktop/selenium/cookie") options.add_argument('--start-maximized') service = webdriver.ChromeService(executable_path='chromedriver.exe') driver = webdriver.Chrome(service=service, options=options) try: # 打开目标网站 driver.get("https://www.youkuaiyun.com/") # 等待页面加载完成 time.sleep(5) finally: pass 运行后报错:Traceback (most recent call last): File "C:\Users\fzh13\Desktop\selenium\test.py", line 18, in <module> driver = webdriver.Chrome(service=service, options=options) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__ super().__init__( File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 66, in __init__ super().__init__(command_executor=executor, options=options) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 241, in __init__ self.start_session(capabilities) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 329, in start_session response = self.execute(Command.NEW_SESSION, caps)["value"] File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 384, in execute self.error_handler.check_response(response) File "D:\DeepLearning\anaconda\envs\chatelink\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.SessionN
03-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值