对于PythonSelenium:登录网站后,WebElement根本无法工作,因为DOM已更新感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解selenium登录后webdriver对象无
对于Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解selenium登录后webdriver对象无法操作,并且为您提供关于
- Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新(selenium登录后webdriver对象无法操作)
- DOM、SAX、JDOM DOM、JDOM SAX、DOM4J DOM、DOM4J SAX 性能比对
- Java Selenium Webdriver - 在运行时从 html DOM 中删除 webelement 时出现循环问题
- org.openqa.selenium.WebDriverException:无法将返回值转换为 WebElement
Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新(selenium登录后webdriver对象无法操作)
如何解决Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新
我对 Selenium 和抓取非常陌生,我需要一些帮助。我正在尝试通过一个使用 Selenium 提供数据和查询的网站来自动化我的一些工作。
问题是,在登录后,DOM 被刷新,显然这会破坏我的 WebElement,因为我不再能够执行任何 find_element、get 或任何登录完成后的函数类型。我什至尝试手动执行此操作,以便不需要任何刷新、等待时间加载等,因为它在人工监督下:(
如果我使用 driver.submit()而不是 driver.click() 会发生同样的问题>
代码如下:
# import web driver
from selenium import webdriver
import time as time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import webdriverwait
from selenium.webdriver.support import expected_conditions as EC
# specifies the path to the chromedriver.exe
driver = webdriver.Chrome(''/Users/user/bin/chromedriver'')
# driver.get method() will navigate to a page given by the URL address
driver.get(''https://app.dnbhoovers.com/'')
# locate email form by_class_name
username = driver.find_element_by_xpath(''//*[@id="username"]'')
# send_keys() to simulate key strokes
username.send_keys(username)
#Sleep some time
time.sleep(0.5)
# locate submit button by_class_name
log_in_button = driver.find_element_by_class_name(''continue-btn'')
# .click() to mimic button click
log_in_button.click()
#Wait for some seconds as password loads after clicking the contiunue bottom
#try:
driver = webdriverwait(driver,5).until(
EC.presence_of_element_located((By.ID,"password"))
)
time.sleep(3)
# locate password form by_class_name
password = driver.find_element_by_xpath(''//*[@id="password"]'')
time.sleep(0.7)
# send_keys() to simulate key strokes
password.send_keys(password)
#Sleep some time
time.sleep(0.7)
# .click() to mimic button click and Sign in
log_in_button.click()
登录后一切都会停止,如果我尝试键入以下函数,我会收到这些错误(即使在等待页面加载之后):
search = driver.find_element_by_xpath("//input[@search-query'']")
StaleElementReferenceException: stale element reference: element is not attached to the page document
或者,如果我什至尝试这个简单的任务,我会得到以下结果:
driver.get("http://www.google.com")
AttributeError: ''WebElement'' object has no attribute ''get''
这样下去,如果我尝试刷新或按下键盘,我会得到:
webdriver.ActionChains(driver).send_keys(Keys.DOWN).perform()
AttributeError: ''WebElement'' object has no attribute ''w3c''
即使我在 .click() 命令之后添加这行来告诉驱动程序等待搜索输入出现,我也会出错
# ... prevIoUs code...#
log_in_button.click()
#New lines of code
webdriverwait(driver,20).until(
EC.presence_of_element_located((By.XPATH,"//input[@search-query'']"))
)
StaleElementReferenceException: stale element reference: element is not attached to the page document
刷新浏览器也没有任何区别。
如果我检查网站的元素,登录后完全改变,我也看到一些“”
我现在真的很困,所以非常感谢任何帮助!
感谢您抽出时间阅读这篇长文!你可以吃土豆:)
解决方法
我认为是这个问题
driver = WebDriverWait(driver,5).until(
EC.presence_of_element_located((By.ID,"password"))
)
WebDriverWait() 返回一个 WebElement,而您不想这样定义 driver
。
driver.get("http://www.google.com")
AttributeError: ''WebElement'' object has no attribute ''get''
这告诉您 driver
是您不想要的 WebElement
。
尝试等到可点击:
elem = wait.until(EC.element_to_be_clickable((By.XPATH,"//input[@search-query'']")))
elem.click()
尝试 2: 如果有正在运行的 JQuery,请在单击之前尝试运行此脚本:
wait.until(lambda driver: driver.execute_script(''return jQuery.active'') == 0)
wait.until(lambda driver: driver.execute_script(''return document.readyState'') == ''complete'')
如何解决<selenium.webdriver.remote.webelement.WebElement 错误
您好,我正在尝试从我的 Spotify 帐户中获取信息,但是当我执行此操作时出现此错误,请帮助我
错误:
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
# start web driver
driver = webdriver.Chrome(r"C:\\chromedriver")
# get source code
driver.get("https://open.spotify.com/playlist/7pqM33R7ypG8dqxvna6VB7")
driver.implicitly_wait(20)
driver.maximize_window()
login_form = driver.find_elements_by_class_name(''main-view-container__scroll-node-child'')
print(login_form)
# close web driver
driver.close()
解决方法
那不是错误,它是您在 print(login_form) 中打印的 webelement 列表对象
使用类似:
print(login_form[0].text)

DOM、SAX、JDOM DOM、JDOM SAX、DOM4J DOM、DOM4J SAX 性能比对
测试xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>XX号</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>XX组</ADDR>
</VALUE>
</RESULT>
测试代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DOMReader;
import org.dom4j.io.SAXReader;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLParserTest {
@Test
public void testDOMTypeParseXML() throws ParserConfigurationException, SAXException,
IOException {
long lasting =System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);
org.w3c.dom.NodeList nl = doc.getElementsByTagName("VALUE");
for (int i=0;i<nl.getLength();i++){
// System.out.print("车牌号码:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
// System.out.println("车主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
}
long end = System.currentTimeMillis();
System.out.println("DOM TYPE PARSE COST "+(end - lasting)+"毫秒");
}
public class MyXMLReader extends DefaultHandler{
@SuppressWarnings("rawtypes")
java.util.Stack tags = new java.util.Stack();
public MyXMLReader() {
super();
}
@SuppressWarnings("unchecked")
public void startElement(String uri,String localName,String qName,Attributes attrs) {
tags.push(qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
// System.out.print("车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
// System.out.println("地址:" + new String(ch, start, length));
}
}
}
@Test
public void testSAXTypeParseXML() throws SAXException, IOException, ParserConfigurationException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
MyXMLReader me = new MyXMLReader();
sp.parse(is, me);
System.out.println("SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
@Test
public void testJDOMSAXTypeParseXML(){
long lasting = System.currentTimeMillis();
try {
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXBuilder builder = new SAXBuilder();
org.jdom.Document doc = builder.build(is);
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i < allChildren.size();i++) {
// System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText());
// System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("JDOM SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
@Test
public void testJDOMDOMTypeParseXML(){
long lasting = System.currentTimeMillis();
try {
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(is);
DOMBuilder builder1 = new DOMBuilder();
org.jdom.Document doc = builder1.build(document);
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i < allChildren.size();i++) {
// System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText());
// System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("JDOM DOM TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
@Test
public void testDOM4JSAXTypeParserXML() throws DocumentException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
org.dom4j.Element root = doc.getRootElement();
org.dom4j.Element foo;
for (Iterator i = root.elementIterator("VALUE");i.hasNext();){
foo = (org.dom4j.Element)i.next();
// System.out.print("车牌号码:" + foo.elementText("NO"));
// System.out.println("车主地址:" + foo.elementText("ADDR"));
}
System.out.println("DOM4J SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
@Test
public void testDOM4JDOMTypeParserXML() throws DocumentException, ParserConfigurationException, SAXException, IOException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(is);
DOMReader reader = new DOMReader();
Document doc = reader.read(document);
org.dom4j.Element root = doc.getRootElement();
org.dom4j.Element foo;
for (Iterator i = root.elementIterator("VALUE");i.hasNext();){
foo = (org.dom4j.Element)i.next();
// System.out.print("车牌号码:" + foo.elementText("NO"));
// System.out.println("车主地址:" + foo.elementText("ADDR"));
}
System.out.println("DOM4J DOM TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
结论:
当测试xml文件大小为50kb左右时:
DOM TYPE PARSE COST 144毫秒
SAX TYPE PARSE COST 43毫秒
JDOM SAX TYPE PARSE COST 179毫秒
JDOM DOM TYPE PARSE COST 145毫秒
DOM4J SAX TYPE PARSE COST 128毫秒
DOM4J DOM TYPE PARSE COST 106毫秒

Java Selenium Webdriver - 在运行时从 html DOM 中删除 webelement 时出现循环问题
如何解决Java Selenium Webdriver - 在运行时从 html DOM 中删除 webelement 时出现循环问题
我有申请,我需要从列表中批准 webelement
列表中共有 50 项
步骤-
- 双击第一个 webelement 并导航到其他页面
- 现在点击批准按钮以批准它
- 页面将再次重定向到列表页面。
现在的问题是当我批准它从列表中删除的元素时,现在我的 for 循环跳过下一个元素,即列表中的 2 个元素,跳转到第三个元素并批准它
在这种情况下,只有 25 个元素获得批准,其余元素仍处于待处理状态
任何逻辑帮助将不胜感激
谢谢,
拉维
解决方法
在没有看到您的代码的情况下,我将假设您正在遍历列表并在每次遍历循环时递增 1。
由于第一个元素在批准后从列表中删除,因此第二个元素成为第一个元素。并且因为您的循环递增 1,所以它会转到列表中的第二个元素。
我的建议是使用 while {} 而不是 for 循环,它将选择并批准列表中的第一个元素,而列表的大小为 >= 1。这样你就应该得到它们。
在伪代码中:
while (element.size >= 1) {
// approve element at first index
}

org.openqa.selenium.WebDriverException:无法将返回值转换为 WebElement
如何解决org.openqa.selenium.WebDriverException:无法将返回值转换为 WebElement
我想为网站编写 selenium 测试。但我还不能让它工作。
这是一个最小的不工作示例。我创建了一个公共 docker 实例。你能重现这个错误吗?执行此代码时是否发生同样的事情?
package Selenium;
import java.net.URL;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class stackoverflow {
@Test
public void testSimple() throws Exception {
DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setbrowserName("firefox");
desiredCapabilities.setVersion("83.0");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://stackoverflow.martin-mandelkow.de:4444/wd/hub"),desiredCapabilities);
driver.get("https://stackoverflow.com/questions/65555131/org-openqa-selenium-webdriverexception-returned-value-cannot-be-converted-to-we");
By containerBy = By.id("notify-container");
WebElement element = driver.findElement(containerBy);
System.out.println(element.toString());
driver.quit();
}
}
控制台日志:
cd C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1; "JAVA_HOME=C:\\\\Program Files\\\\Java\\\\jdk-15.0.1" cmd /c "\\"C:\\\\Program Files\\\\NetBeans-12.2\\\\netbeans\\\\java\\\\maven\\\\bin\\\\mvn.cmd\\" -Dtest=Selenium.stackoverflow -Dmaven.ext.class.path=\\"C:\\\\Program Files\\\\NetBeans-12.2\\\\netbeans\\\\java\\\\maven-nblib\\\\netbeans-eventspy.jar\\" -Dfile.encoding=UTF-8 test-compile surefire:test"
Scanning for projects...
--------------------< com.mycompany:mavenproject1 >---------------------
Building mavenproject1 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- maven-resources-plugin:2.6:resources (default-resources) @ mavenproject1 ---
Using ''UTF-8'' encoding to copy filtered resources.
skip non existing resourceDirectory C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\src\\main\\resources
--- maven-compiler-plugin:3.1:compile (default-compile) @ mavenproject1 ---
nothing to compile - all classes are up to date
--- maven-resources-plugin:2.6:testResources (default-testResources) @ mavenproject1 ---
Using ''UTF-8'' encoding to copy filtered resources.
skip non existing resourceDirectory C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\src\\test\\resources
--- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ mavenproject1 ---
Changes detected - recompiling the module!
Compiling 6 source files to C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\test-classes
--- maven-surefire-plugin:2.12.4:test (default-cli) @ mavenproject1 ---
Surefire report directory: C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running Selenium.stackoverflow
element = driver.findElement
Tests run: 1,Failures: 0,Errors: 1,Skipped: 0,Time elapsed: 6.705 sec <<< FAILURE!
testSimple(Selenium.stackoverflow) Time elapsed: 6.552 sec <<< ERROR!
org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=18ace72e-f260-4c78-a78b-b34a8f3cf8d4}
Build info: version: ''2.45.0'',revision: ''5017cb8e7ca8e37638dc3091b2440b90a1d8686f'',time: ''2015-02-27 09:10:26''
System info: host: ''DESKTOP-NSVVQ0T'',ip: ''172.20.176.1'',os.name: ''Windows 10'',os.arch: ''amd64'',os.version: ''10.0'',java.version: ''15.0.1''
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:359)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at Selenium.stackoverflow.testSimple(stackoverflow.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runchildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.classCastException: class com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to class org.openqa.selenium.WebElement (com.google.common.collect.Maps$TransformedEntriesMap and org.openqa.selenium.WebElement are in unnamed module of loader ''app'')
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:357)
... 36 more
Results :
Tests in error:
testSimple(Selenium.stackoverflow): Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=18ace72e-f260-4c78-a78b-b34a8f3cf8d4}(..)
Tests run: 1,Skipped: 0
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 15.319 s
Finished at: 2021-01-06T20:28:51+01:00
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-cli) on project mavenproject1: There are test failures.
Please refer to C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\surefire-reports for the individual test results.
-> [Help 1]
To see the full stack trace of the errors,re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions,please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-remote-driver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
<version>2.45.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
我在这里错过了什么?这是Java依赖的问题吗? docker selenium 镜像有问题吗?
关于Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新和selenium登录后webdriver对象无法操作的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于等相关内容,可以在本站寻找。
本文标签:
如何解决<selenium.webdriver.remote.webelement.WebElement 错误
您好,我正在尝试从我的 Spotify 帐户中获取信息,但是当我执行此操作时出现此错误,请帮助我
错误:
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys
# start web driver
driver = webdriver.Chrome(r"C:\\chromedriver")
# get source code
driver.get("https://open.spotify.com/playlist/7pqM33R7ypG8dqxvna6VB7")
driver.implicitly_wait(20)
driver.maximize_window()
login_form = driver.find_elements_by_class_name(''main-view-container__scroll-node-child'')
print(login_form)
# close web driver
driver.close()
解决方法
那不是错误,它是您在 print(login_form) 中打印的 webelement 列表对象
使用类似:
print(login_form[0].text)
DOM、SAX、JDOM DOM、JDOM SAX、DOM4J DOM、DOM4J SAX 性能比对
测试xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<RESULT>
<VALUE>
<NO>A1234</NO>
<ADDR>XX号</ADDR>
</VALUE>
<VALUE>
<NO>B1234</NO>
<ADDR>XX组</ADDR>
</VALUE>
</RESULT>
测试代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DOMReader;
import org.dom4j.io.SAXReader;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import org.jdom.input.SAXBuilder;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLParserTest {
@Test
public void testDOMTypeParseXML() throws ParserConfigurationException, SAXException,
IOException {
long lasting =System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);
org.w3c.dom.NodeList nl = doc.getElementsByTagName("VALUE");
for (int i=0;i<nl.getLength();i++){
// System.out.print("车牌号码:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue());
// System.out.println("车主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue());
}
long end = System.currentTimeMillis();
System.out.println("DOM TYPE PARSE COST "+(end - lasting)+"毫秒");
}
public class MyXMLReader extends DefaultHandler{
@SuppressWarnings("rawtypes")
java.util.Stack tags = new java.util.Stack();
public MyXMLReader() {
super();
}
@SuppressWarnings("unchecked")
public void startElement(String uri,String localName,String qName,Attributes attrs) {
tags.push(qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
String tag = (String) tags.peek();
if (tag.equals("NO")) {
// System.out.print("车牌号码:" + new String(ch, start, length));
}
if (tag.equals("ADDR")) {
// System.out.println("地址:" + new String(ch, start, length));
}
}
}
@Test
public void testSAXTypeParseXML() throws SAXException, IOException, ParserConfigurationException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXParserFactory sf = SAXParserFactory.newInstance();
SAXParser sp = sf.newSAXParser();
MyXMLReader me = new MyXMLReader();
sp.parse(is, me);
System.out.println("SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
@Test
public void testJDOMSAXTypeParseXML(){
long lasting = System.currentTimeMillis();
try {
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXBuilder builder = new SAXBuilder();
org.jdom.Document doc = builder.build(is);
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i < allChildren.size();i++) {
// System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText());
// System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("JDOM SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
@Test
public void testJDOMDOMTypeParseXML(){
long lasting = System.currentTimeMillis();
try {
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(is);
DOMBuilder builder1 = new DOMBuilder();
org.jdom.Document doc = builder1.build(document);
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i < allChildren.size();i++) {
// System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText());
// System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
System.out.println("JDOM DOM TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
@Test
public void testDOM4JSAXTypeParserXML() throws DocumentException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
org.dom4j.Element root = doc.getRootElement();
org.dom4j.Element foo;
for (Iterator i = root.elementIterator("VALUE");i.hasNext();){
foo = (org.dom4j.Element)i.next();
// System.out.print("车牌号码:" + foo.elementText("NO"));
// System.out.println("车主地址:" + foo.elementText("ADDR"));
}
System.out.println("DOM4J SAX TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
@Test
public void testDOM4JDOMTypeParserXML() throws DocumentException, ParserConfigurationException, SAXException, IOException{
long lasting = System.currentTimeMillis();
InputStream is = XMLParserTest.class.getClassLoader().getResourceAsStream("test.xml");
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(is);
DOMReader reader = new DOMReader();
Document doc = reader.read(document);
org.dom4j.Element root = doc.getRootElement();
org.dom4j.Element foo;
for (Iterator i = root.elementIterator("VALUE");i.hasNext();){
foo = (org.dom4j.Element)i.next();
// System.out.print("车牌号码:" + foo.elementText("NO"));
// System.out.println("车主地址:" + foo.elementText("ADDR"));
}
System.out.println("DOM4J DOM TYPE PARSE COST "+(System.currentTimeMillis() - lasting)+"毫秒");
}
}
结论:
当测试xml文件大小为50kb左右时:
DOM TYPE PARSE COST 144毫秒
SAX TYPE PARSE COST 43毫秒
JDOM SAX TYPE PARSE COST 179毫秒
JDOM DOM TYPE PARSE COST 145毫秒
DOM4J SAX TYPE PARSE COST 128毫秒
DOM4J DOM TYPE PARSE COST 106毫秒
Java Selenium Webdriver - 在运行时从 html DOM 中删除 webelement 时出现循环问题
如何解决Java Selenium Webdriver - 在运行时从 html DOM 中删除 webelement 时出现循环问题
我有申请,我需要从列表中批准 webelement 列表中共有 50 项 步骤-
- 双击第一个 webelement 并导航到其他页面
- 现在点击批准按钮以批准它
- 页面将再次重定向到列表页面。
现在的问题是当我批准它从列表中删除的元素时,现在我的 for 循环跳过下一个元素,即列表中的 2 个元素,跳转到第三个元素并批准它
在这种情况下,只有 25 个元素获得批准,其余元素仍处于待处理状态
任何逻辑帮助将不胜感激
谢谢, 拉维
解决方法
在没有看到您的代码的情况下,我将假设您正在遍历列表并在每次遍历循环时递增 1。 由于第一个元素在批准后从列表中删除,因此第二个元素成为第一个元素。并且因为您的循环递增 1,所以它会转到列表中的第二个元素。
我的建议是使用 while {} 而不是 for 循环,它将选择并批准列表中的第一个元素,而列表的大小为 >= 1。这样你就应该得到它们。
在伪代码中:
while (element.size >= 1) {
// approve element at first index
}
org.openqa.selenium.WebDriverException:无法将返回值转换为 WebElement
如何解决org.openqa.selenium.WebDriverException:无法将返回值转换为 WebElement
我想为网站编写 selenium 测试。但我还不能让它工作。
这是一个最小的不工作示例。我创建了一个公共 docker 实例。你能重现这个错误吗?执行此代码时是否发生同样的事情?
package Selenium;
import java.net.URL;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class stackoverflow {
@Test
public void testSimple() throws Exception {
DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setbrowserName("firefox");
desiredCapabilities.setVersion("83.0");
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://stackoverflow.martin-mandelkow.de:4444/wd/hub"),desiredCapabilities);
driver.get("https://stackoverflow.com/questions/65555131/org-openqa-selenium-webdriverexception-returned-value-cannot-be-converted-to-we");
By containerBy = By.id("notify-container");
WebElement element = driver.findElement(containerBy);
System.out.println(element.toString());
driver.quit();
}
}
控制台日志:
cd C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1; "JAVA_HOME=C:\\\\Program Files\\\\Java\\\\jdk-15.0.1" cmd /c "\\"C:\\\\Program Files\\\\NetBeans-12.2\\\\netbeans\\\\java\\\\maven\\\\bin\\\\mvn.cmd\\" -Dtest=Selenium.stackoverflow -Dmaven.ext.class.path=\\"C:\\\\Program Files\\\\NetBeans-12.2\\\\netbeans\\\\java\\\\maven-nblib\\\\netbeans-eventspy.jar\\" -Dfile.encoding=UTF-8 test-compile surefire:test"
Scanning for projects...
--------------------< com.mycompany:mavenproject1 >---------------------
Building mavenproject1 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------
--- maven-resources-plugin:2.6:resources (default-resources) @ mavenproject1 ---
Using ''UTF-8'' encoding to copy filtered resources.
skip non existing resourceDirectory C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\src\\main\\resources
--- maven-compiler-plugin:3.1:compile (default-compile) @ mavenproject1 ---
nothing to compile - all classes are up to date
--- maven-resources-plugin:2.6:testResources (default-testResources) @ mavenproject1 ---
Using ''UTF-8'' encoding to copy filtered resources.
skip non existing resourceDirectory C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\src\\test\\resources
--- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ mavenproject1 ---
Changes detected - recompiling the module!
Compiling 6 source files to C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\test-classes
--- maven-surefire-plugin:2.12.4:test (default-cli) @ mavenproject1 ---
Surefire report directory: C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running Selenium.stackoverflow
element = driver.findElement
Tests run: 1,Failures: 0,Errors: 1,Skipped: 0,Time elapsed: 6.705 sec <<< FAILURE!
testSimple(Selenium.stackoverflow) Time elapsed: 6.552 sec <<< ERROR!
org.openqa.selenium.WebDriverException: Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=18ace72e-f260-4c78-a78b-b34a8f3cf8d4}
Build info: version: ''2.45.0'',revision: ''5017cb8e7ca8e37638dc3091b2440b90a1d8686f'',time: ''2015-02-27 09:10:26''
System info: host: ''DESKTOP-NSVVQ0T'',ip: ''172.20.176.1'',os.name: ''Windows 10'',os.arch: ''amd64'',os.version: ''10.0'',java.version: ''15.0.1''
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:359)
at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:393)
at org.openqa.selenium.By$ById.findElement(By.java:214)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:344)
at Selenium.stackoverflow.testSimple(stackoverflow.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runchild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runchildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.classCastException: class com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to class org.openqa.selenium.WebElement (com.google.common.collect.Maps$TransformedEntriesMap and org.openqa.selenium.WebElement are in unnamed module of loader ''app'')
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:357)
... 36 more
Results :
Tests in error:
testSimple(Selenium.stackoverflow): Returned value cannot be converted to WebElement: {element-6066-11e4-a52e-4f735466cecf=18ace72e-f260-4c78-a78b-b34a8f3cf8d4}(..)
Tests run: 1,Skipped: 0
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 15.319 s
Finished at: 2021-01-06T20:28:51+01:00
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-cli) on project mavenproject1: There are test failures.
Please refer to C:\\Users\\Mandelkow\\Documents\\NetBeansprojects\\mavenproject1\\target\\surefire-reports for the individual test results.
-> [Help 1]
To see the full stack trace of the errors,re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.
For more information about the errors and possible solutions,please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany</groupId>
<artifactId>mavenproject1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-remote-driver -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-remote-driver</artifactId>
<version>2.45.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
我在这里错过了什么?这是Java依赖的问题吗? docker selenium 镜像有问题吗?
关于Python Selenium:登录网站后,WebElement 根本无法工作,因为 DOM 已更新和selenium登录后webdriver对象无法操作的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于
本文标签: