GVKun编程网logo

selenium很多日志(如何删除)(selenium 日志)

17

本文将带您了解关于selenium很多日志的新内容,同时我们还将为您解释如何删除的相关知识,另外,我们还将为您提供关于c#–是否可以在不安装SeleniumServer的情况下使用ISelenium/

本文将带您了解关于selenium很多日志的新内容,同时我们还将为您解释如何删除的相关知识,另外,我们还将为您提供关于c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?、java+selenium, python+selenium浏览界面,滑动页面、Python Selenium,如何删除元素?、python+selenium十:selenium的二次封装的实用信息。

本文目录一览:

selenium很多日志(如何删除)(selenium 日志)

selenium很多日志(如何删除)(selenium 日志)

我在 Firefox 48上 尝试了 Selenium 3.0.1。

我已经尝试了以下代码:

java.util.logging.Logger.getLogger(“
com.gargoylesoftware.htmlunit”)。setLevel(Level.OFF);
java.util.logging.Logger.getLogger(“
org.apache.commons.httpclient”)。setLevel(Level.OFF);
java.util.logging.Logger.getLogger(ProtocolHandshake.class.getName())。setLevel(Level.OFF);

但是一旦我在 Netbeans 下运行常规测试,…日志仍然出现:

Dec 02, 2016 9:17:53 AM org.openqa.selenium.remote.ProtocolHandshake createSessionINFO: Attempting bi-dialect session, assuming Postel''s Law holds true on the remote endDec 02, 2016 9:17:57 AM org.openqa.selenium.remote.ProtocolHandshake createSessionINFO: Detected dialect: OSS

有解决这个问题的线索吗?

答案1

小编典典

您必须将记录器固定在内存中或设置logging.properties配置文件。从java.util.logging.Logger文档中:

可以通过调用getLogger工厂方法之一获得Logger对象。这些将创建一个新的Logger或返回一个合适的现有Logger。重要的是要注意,如果没有保留对Logger的强引用,则getLogger工厂方法之一返回的Logger随时可能被垃圾回收。

返回新的记录器时,日志级别由LogManager确定,默认情况下,LogManager使用logging.properties文件中的设置。在您的示例中,可能会看到以下内容:

  1. 调用getLogger创建一个新的记录器,并从LogManager设置级别。
  2. 您的代码将记录器级别设置为OFF。
  3. GC会运行并破坏您的记录器以及您刚刚应用的设置。
  4. Selenium调用getLogger并创建一个新的记录器,并从LogManager设置级别。

下面是一个测试用例示例,以证明这一点:

    public static void main(String[] args) {        String name = "com.gargoylesoftware.htmlunit";        for (int i = 0; i < 5; i++) {            System.out.println(Logger.getLogger(name).getLevel());            Logger.getLogger(name).setLevel(Level.OFF);            System.runFinalization();            System.gc();            System.runFinalization();            Thread.yield();        }    }

将输出null而不是OFF

如果您通过保持强烈的参考力来固定记录器,那么步骤3就永远不会发生,Selenium应该找到您创建的记录器,并将其级别设置为OFF。

private static final Logger[] pin;static {    pin = new Logger[]{        Logger.getLogger("com.gargoylesoftware.htmlunit"),        Logger.getLogger("org.apache.commons.httpclient"),        Logger.getLogger("org.openqa.selenium.remote.ProtocolHandshake")    };    for (Logger l : pin) {        l.setLevel(Level.OFF);    }}

c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?

c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?

我之前使用IWebDriver控制IE进行测试.但是IWebDriver和IWebElement支持的方法非常有限.我发现属于Selenium命名空间的ISelenium / DefaultSelenium非常有用.如何在不安装Selenium Server的情况下使用它们来控制IE?

这是DefaultSelenium的构造函数:

ISelenium sele = new DefaultSelenium(**serveraddr**,**serverport**,browser,url2test);
sele.Start();
sele.open();
...

似乎我必须在创建ISelenium对象之前安装Selenium Server.

我的情况是,我正在尝试使用C#Selenium构建一个.exe应用程序,它可以在不同的PC上运行,并且不可能在所有PC上安装Selenium Server(你永远不知道哪个是下一个运行应用程序).

有没有人知道如何在不安装服务器的情况下使用ISelenium / DefaultSelenium?
谢谢!

解决方法

在不使用RC Server的情况下,Java中有一些解决方案:

1)对于selenium浏览器启动:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setbrowserName("safari");
CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"),new URL("http://www.google.com/"),capabilities);
WebDriver driver = new RemoteWebDriver(executor,capabilities);

2)对于selenium命令:

// You may use any WebDriver implementation. Firefox is used here as an example
WebDriver driver = new FirefoxDriver();

// A "base url",used by selenium to resolve relative URLs
 String baseUrl = "http://www.google.com";

// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver,baseUrl);

// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q","cheese");
selenium.click("name=btnG");

// Get the underlying WebDriver implementation back. This will refer to the
// same WebDriver instance as the "driver" variable above.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();

//Finally,close the browser. Call stop on the WebDriverBackedSelenium instance
//instead of calling driver.quit(). Otherwise,the JVM will continue running after
//the browser has been closed.
selenium.stop();

描述于此:http://seleniumhq.org/docs/03_webdriver.html

谷歌在C#中有类似的东西.没有其他方法可以实现这一目标.

java+selenium, python+selenium浏览界面,滑动页面

java+selenium, python+selenium浏览界面,滑动页面

用到selenium的时候,有时需要滑动屏幕,模拟浏览,这时候就可以用到下边的代码了:

首先是java的selenium滑屏代码(不知道为啥后边就乱了排版,自己调整下就好~)

private static Random random = new Random();
private void pretendScrolling(JavascriptExecutor js, int sum) throws InterruptedException {
sum--;
int step;
int length;
switch (sum) {
case 0:
step = random.nextInt(30) + 1 + 50;
length = random.nextInt(3000) + 1 + 3000;
smoothlyScrolling(js, 0, step, length, true);
smoothlyScrolling(js, 0, step, length, false);

smoothlyScrolling(js, 0, step, length, true);
smoothlyScrolling(js, length, step, 8000, true);

step = random.nextInt(20) + 1 + 80;
smoothlyScrolling(js, 0, step, 8000, false);

length = random.nextInt(2000) + 1 + 3000;
smoothlyScrolling(js, 0, step, length, true);
smoothlyScrolling(js, 0, 20, length, false);
break;
case 1:
step = random.nextInt(10) + 1 + 40;
smoothlyScrolling(js, 0, step, 6000, true);
Thread.sleep(3000);
smoothlyScrolling(js, 0, step, 6000, false);

length = random.nextInt(1500) + 1 + 1000;
step = random.nextInt(10) + 1 + 40;
Thread.sleep(3000);
smoothlyScrolling(js, 0, step, length, true);
Thread.sleep(5000);
step = random.nextInt(10) + 1 + 40;
smoothlyScrolling(js, length, step, 7000, true);
Thread.sleep(3000);

step = random.nextInt(20) + 1 + 80;
smoothlyScrolling(js, 0, step, 8000, false);
Thread.sleep(3000);
break;
case 2:
step = random.nextInt(10) + 1 + 30;
length = random.nextInt(1300) + 1 + 1000;
smoothlyScrolling(js, 0, step, length, true); Thread.sleep(8000); step = random.nextInt(10) + 1 + 20; smoothlyScrolling(js, length, step, 6000, true); Thread.sleep(3000); length = random.nextInt(1500) + 1 + 1500; step = random.nextInt(20) + 1 + 40; smoothlyScrolling(js, length, step, 6000, false); Thread.sleep(3000); step = random.nextInt(30) + 1 + 70;
smoothlyScrolling(js, length, step, 6000, true);
Thread.sleep(4000);
step = random.nextInt(20) + 1 + 30;
smoothlyScrolling(js, 0, step, 6000, false);
Thread.sleep(3000);
break;
case 3:
step = random.nextInt(10) + 1 + 30;
smoothlyScrolling(js, 0, step, 7000, true);
Thread.sleep(3000);
step = random.nextInt(30) + 1 + 20;
smoothlyScrolling(js, 0, step, 7000, false);
Thread.sleep(3000);
break;
case 4:
step = random.nextInt(10) + 1 + 50;
smoothlyScrolling(js, 0, step, 7000, true);
Thread.sleep(3000);
length = random.nextInt(1500) + 1 + 2000;
step = random.nextInt(25) + 1 + 20;
smoothlyScrolling(js, length, step, 7000, false);
Thread.sleep(3000);
step = random.nextInt(20) + 1 + 30;
smoothlyScrolling(js, length, step, 7000, true);
Thread.sleep(3000);
step = random.nextInt(20) + 1 + 40;
smoothlyScrolling(js, 0, step, 7000, false);
Thread.sleep(2000);
break;
case 5:
step = random.nextInt(20) + 1 + 30;
smoothlyScrolling(js, 0, step, 2500, true);
Thread.sleep(3000);
step = random.nextInt(30) + 1 + 40;
smoothlyScrolling(js, 0, step, 2500, false);
Thread.sleep(3000);
step = random.nextInt(20) + 1 + 30;
smoothlyScrolling(js, 0, step, 7000, true);
Thread.sleep(6000);
step = random.nextInt(20) + 1 + 30;
smoothlyScrolling(js, 0, step, 7000, false);
Thread.sleep(2000);
break;
default:
case 6:
step = random.nextInt(30) + 1 + 30;
length = random.nextInt(1500) + 1 + 2500;
smoothlyScrolling(js, 0, step, length, true);
step = random.nextInt(30) + 1 + 70;
smoothlyScrolling(js, 0, step, length, false);
step = random.nextInt(20) + 1 + 40;
smoothlyScrolling(js, 0, step, 7000, true);
step = random.nextInt(25) + 1 + 20;
smoothlyScrolling(js, 0, step, 7000, false);
Thread.sleep(3000);
step = random.nextInt(25) + 1 + 20;
length = random.nextInt(1500) + 1 + 3000;
smoothlyScrolling(js, 0, step, length, true);
Thread.sleep(3000);
step = random.nextInt(15) + 1 + 30;
smoothlyScrolling(js, 0, step, length, false);
break;
}
}
private void smoothlyScrolling(JavascriptExecutor js, int floor, int step, int celling, boolean direction) {
if (direction) {
for (int i = floor; i <= celling; i += step) {
js.executeScript("scrollTo(0," + i + ")");
}
} else {
for (int i = celling; i >= floor; i -= step) {
js.executeScript("scrollTo(0," + i + ")");
}
}
}

用法如下:



两个参数,其中js表示的是driver, sum是一个随机数,表示随机的从7中浏览方式之间选一种


再然后是在python selenium中的应用,我专门写了一个类出来存放浏览界面的代码,然后在需要用到它的地方导入,引用
import random
import time


class PretendScrolling:
@staticmethod
def pretend_scrolling(driver, sum):
step = 1
length = 1
if sum == 1:
step = random.randint(0, 30) + 1 + 50
length = random.randint(0, 3000) + 1 + 3000
smoothlyScrolling(driver, 0, step, length, True)
smoothlyScrolling(driver, 0, step, length, False)

smoothlyScrolling(driver, 0, step, length, True)
smoothlyScrolling(driver, length, step, 8000, False)
step = random.randint(0, 20)+ 1+80
smoothlyScrolling(driver, 0 ,step, 8000, False)

length = random.randint(0, 2000) + 1 + 3000
smoothlyScrolling(driver, 0 , step, length, True)
smoothlyScrolling(driver, 0 , 20, length, False)
elif sum == 2:
step = random.randint(0, 10) + 1 + 40
smoothlyScrolling(driver, 0, step, 6000, True)
time.sleep(3)
smoothlyScrolling(driver, 0, step, 6000, False)

length = random.randint(0, 1500) + 1 + 1000
step = random.randint(0, 10) + 1 + 40
time.sleep(3)
smoothlyScrolling(driver, 0, step, length, True)
time.sleep(5)
step = random.randint(0, 10)+1+40
smoothlyScrolling(driver, length, step, 7000, True)
time.sleep(3)

step = random.randint(0, 20)+1+80
smoothlyScrolling(driver, 0, step, 8000, False)
time.sleep(3)
elif sum == 3:
step = random.randint(0, 10) + 1 + 30
length = random.randint(0, 1300) + 1 + 1000
smoothlyScrolling(driver, 0, step, length, True)
time.sleep(8)
step = random.randint(0, 10) + 1 + 20
smoothlyScrolling(driver, length, step, 6000, True)
time.sleep(3)
length = random.randint(0, 1500) + 1 + 1500
step = random.randint(0, 20) + 1 + 40
smoothlyScrolling(driver, length, step, 6000, False)
time.sleep(3)
step = random.randint(0, 30) + 1 + 70
smoothlyScrolling(driver, length, step, 6000, True)
time.sleep(4)
step = random.randint(0, 20) + 1 + 30
smoothlyScrolling(driver, 0, step, 6000, False)
time.sleep(3)
elif sum == 4:
step = random.randint(0, 10) + 1 + 30
smoothlyScrolling(driver, 0, step, 7000, True)
time.sleep(3)
step = random.randint(0, 30) + 1 + 20
smoothlyScrolling(driver, 0, step, 7000, False)
time.sleep(3)
elif sum == 5:
step = random.randint(0, 10) + 1 + 50
smoothlyScrolling(driver, 0, step, 7000, True)
time.sleep(3)
length = random.randint(0, 1500) + 1 + 2000
step = random.randint(0, 25) + 1 + 20
smoothlyScrolling(driver, length, step, 7000, False)
time.sleep(3)
step = random.randint(0, 20) + 1 + 30
smoothlyScrolling(driver, length, step, 7000, True) time.sleep(3) step = random.randint(0, 20) + 1 + 40 smoothlyScrolling(driver, 0, step, 7000, False) time.sleep(2) elif sum == 6: step = random.randint(0, 20) + 1 + 30 smoothlyScrolling(driver, 0, step, 2500, True) time.sleep(3)
step = random.randint(0, 30) + 1 + 40
smoothlyScrolling(driver, 0, step, 2500, False)
time.sleep(3)
step = random.randint(0, 20) + 1 + 30
smoothlyScrolling(driver, 0, step, 7000, True)
time.sleep(6)
step = random.randint(0, 20) + 1 + 30
smoothlyScrolling(driver, 0, step, 7000, False)
time.sleep(2)
elif sum == 7:
step = random.randint(0, 30) + 1 + 30
length = random.randint(0, 1500) + 1 + 2500
smoothlyScrolling(driver, 0, step, length, True)
step = random.randint(0, 30) + 1 + 70
smoothlyScrolling(driver, 0, step, length, False)
step = random.randint(0, 20) + 1 + 40
smoothlyScrolling(driver, 0, step, 7000, True)
step = random.randint(0, 25) + 1 + 20
smoothlyScrolling(driver, 0, step, 7000, False)
time.sleep(3)
step = random.randint(0, 25) + 1 + 20
length = random.randint(0, 1500) + 1 + 3000
smoothlyScrolling(driver, 0, step, length, True)
time.sleep(3)
step = random.randint(0, 15) + 1 + 30
smoothlyScrolling(driver, 0, step, length, False)
else:
pass



#(不知道为啥会乱排版,这是另一个方法)def smoothlyScrolling(driver, floor, step, celling, direction):
if direction is True:
i = floor
while i <= celling:
i += step
jscript = "window.scrollTo(1, {height_i})".format(height_i=i)
driver.execute_script(jscript)
else:
i = celling
while i >= floor:
i -= step
jscript = "window.scrollTo(1, {height_i})".format(height_i=i)
driver.execute_script(jscript)



 







在python的其它类中引用如下:
首先先在相关类中引入滚动界面的类

 

然后调用:
以上就是selenium里边滑动界面的一组方法了,支持java和python.
 





因为图片好像没有加载出来,所以再放一下.然后也不知道为啥排版会乱,要用的话自己调整一下即可.

 



 

 


  

 

 

Python Selenium,如何删除元素?

Python Selenium,如何删除元素?

如何解决Python Selenium,如何删除元素??

getElementByClassName不是的方法document。您将要使用

getElementsByClassName(''classname'')[0]...

但前提是您确定它是该课程中唯一的课程。

解决方法

我一直在尝试最后一小时删除元素,但没有成功。而且该元素只能通过类名来访问。我试过了:

js = "var aa=document.getElementsByClassName(''classname'')[0];aa.parentNode.removeChild(aa)"
driver.execute_script(js)

我收到未定义parentNode的错误。

那么,使用Selenium删除元素的最佳方法是什么?

python+selenium十:selenium的二次封装

python+selenium十:selenium的二次封装

python+selenium十:基于原生selenium的二次封装

 
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
# BY的用法
# driver.find_element("id", "kw")
# driver.find_element(By.ID, "kw")

class Bace():
''''''基于原生的selenium做二次封装''''''

def __init__(self, driver:webdriver.Firefox): # driver:webdriver.Firefox:映射driver 为webdriver.Firefox
self.driver = driver
self.timeout = 10
self.t = 0.5

def find(self, locator, value=''''):
'''''' 定位到元素,返回元素对象,没定位到,Timeout异常 loctor 传元祖,如("id", "kw") ''''''
if not isinstance(locator, tuple):
print(''locator参数类型错误,必须传元祖类型:loc = ("id", "value1")'')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '''': # value值定位
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return ele
else: # 默认为此常规定位方法
ele = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if ele:
return ele
else:
print(f"定位失败:定位方式->{locator[0]}, value值->{locator[1]}")
return False

def finds(self, locator, value=''''):
'''''' 定位到元素,返回元素对象,没定位到,Timeout异常 loctor 传元祖,如("id", "kw") ''''''
if not isinstance(locator, tuple):
print(''locator参数类型错误,必须传元祖类型:loc = ("id", "value1")'')
else:
print(f"正在定位元素信息:定位方式->{locator[0]}, 元素值->{locator[1]},value值->{value}")
if value != '''': # value值定位
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, value))
return eles
else: # 默认为此常规定位方法
eles = WebDriverWait(self.driver, self.timeout, self.t).until(EC.presence_of_element_located(locator))
if eles:
return eles
else:
print(f"定位失败:定位方式->{locator[0]}, value值->{locator[1]}")
return []

def sendKeys(self, locator, text):
try:
self.find(locator).send_keys(text)
except:
print(f"输入 {text} 失败")

def click(self, locator):
try:
self.find(locator).click()
except:
print("点击失败")

def clear(self, locator):
try:
self.find(locator).clear()
except:
print("清空内容失败")

def isSelected(self, locator, Type=''''):
'''''' 判断元素是否被选中,返回bool值 及点(选中/取消选中)''''''
ele = self.find(locator)
try:
if Type == '''': # 如果type参数为空,返回元素是否为选中状态,True/False (默认)
r = ele.is_selected()
return r
elif Type == ''click'': # 如果type参数为click,执行元素的点击操作
ele.click()
else:
print(f"type参数 {Type} 错误,仅可为click或''''")
except:
return False

def isElementExist(self, locator):
'''''' 判断单个元素是否在DOM里面 (是否存在)''''''
try:
self.find(locator)
return True
except:
return False

def isElementExists(self, locator):
'''''' 判断一组元素是否在DOM里面 (是否存在),若不存在,返回一个空的list''''''
eles = self.finds(locator)
n = len(eles)
if n == 0:
return False
elif n == 1:
return True
else:
print(f"定位到元素的个数:{n}")
return True

def title(self, title, Type=''contains''):
'''''' 根据传入的type类型判断title ''''''
try:
if Type == ''is'': # 判断当前网页title名为title 返回bool值
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
return result
elif Type == ''contains'': # 判断当前网页title名含title 返回bool值 (默认)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
return result
else:
print(f"type参数 {Type} 错误,仅可为is、contains")
except:
return False

def in_element(self, locator, value, Type=''text''):
'''''' 根据传入的type判断内容是否在指定元素里面 ''''''
if not isinstance(locator, tuple):
print(''locator参数类型错误,必须传元祖类型:loc = ("id", "value1")'')
try:
if Type == ''text'': # 判断当前获取到的text含value 返回bool值 (默认)
result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, value))
return result
elif Type == ''value'': # 判断当前获取到的value含value 返回bool值, value为空字符串,返回False
result = self.find(locator, value)
return result
else:
print(f"type参数 {Type} 错误,仅可使用text或value属性定位")
return False
except:
return False

def alert(self, timeout=3, Type=''''):
'''''' 根据传入的type判断alert弹窗及操作 ''''''
result = WebDriverWait(self.driver, timeout, self.t).until(EC.alert_is_present())
try:
if Type == '''': # 判断alert是否存在,如果有,就返回alert对象 (默认)
if result:
return result
else:
print("alert不存在")
return False
elif Type == ''yes'': # 执行alert的确定按钮
result.accept()
elif Type == ''no'': # 执行alert的取消按钮
result.dismiss()
else:
print(f"type参数 {Type} 错误,仅可为yes、no、或''''")
except:
return False

def get(self, locator, Type=''text'', name=''''):
'''''' 根据传入的type判断获取指定的内容 (title、text、attribute)
type==attribute: 获取元素属性 name:属性 className、name、text、value··· ''''''
try:
if Type == ''title'': # 获取当前网页 title
return self.driver.title
elif Type == ''text'': # 获取元素文本值(默认)
return self.find(locator).text
elif Type == ''attribute'': # 获取当前元素属性
return self.find(locator).get_attribute(name)
else:
print(f"给的type参数 {Type} 错误,仅可用title、text、attribute")
except:
print(f"获取 {Type} 值失败")
return ''''

def select(self, locator, value, Type=''index''):
'''''' 下拉选项框 根据传入的type值判断(index、value、text) ''''''
element = self.find(locator) # 定位select这一栏
try:
if Type == ''index'': # 用下标选择 (默认)
Select(element).select_by_index(value)
elif Type == ''value'': # 根据value值选择
Select(element).select_by_value(value)
elif Type == ''text'': # 根据选项的文本内容选择
Select(element).select_by_visible_text(value)
else:
print(f"给的type参数 {Type} 错误,仅可为:int、text、value")
except:
print(f"根据 {value} 操作下拉框失败")

def iframe(self, id_index_locator):
'''''' 常规切换 iframe''''''
try:
if isinstance(id_index_locator, int): # 如果传入的是数字,则以该数字为下标取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, str): # 如果传入的是字符串,则用iframe名字取值
self.driver.switch_to.frame(id_index_locator)
elif isinstance(id_index_locator, tuple): # 如果是元祖,则根据传入的locator取值
ele = self.find(id_index_locator)
self.driver.switch_to.frame(ele)
except:
print("iframe切换异常")

def handle(self, value):
'''''' 句柄切换,index、句柄名 ''''''
try:
if isinstance(value, int): # 切换到该下标对应的窗口
handles = driver.window_handles
self.driver.switch_to.window(handles[value])
elif isinstance(value, str): # 切换到该句柄名称对应的窗口
self.driver.switch_to.window(value)
else:
print(f"传入的type参数 {value} 错误,仅可传int、str")
except:
print(f"根据 {value} 获取句柄失败")

def move_to_element(self, locator):
'''''' 鼠标悬停操作 ''''''
try:
ele = self.find(locator)
ActionChains(self.driver).move_to_element(ele).perform()
except:
print("鼠标悬停操作失败")
return False
''''''==============================js与jQuery相关=====================================''''''

def js_focus_element(self, locator):
'''''' 聚焦元素 ''''''
target = self.find(locator)
self.driver.execute_script("arguments[0].scrollIntoView();", target)

def js_scroll_top(self):
'''''' 滚动到顶部 ''''''
js = "window.scrollTo(0,0)"
self.driver.execute_script(js)

def js_scroll_end(self, x=0):
'''''' 滚动到底部 ''''''
js = f"window.scrollTo({x},document.body.scrollHeight)"
self.driver.execute_script(js)

def js_find(self, action):
'''''' js查找元素,并做相应操作(默认id属性) 输入值:value=''XXX'' 点击:click() ''''''
js = f"document.getElementById(“id”).{action}"
self.driver.execute_script(js)

def js_finds(self, Type, element, index, action):
'''''' js查找元素,并做相应操作 输入值:value=''XXX'' 点击:click()
js定位仅可为:id、Name、TagName、ClassName、Selector(CSS) ''''''
list = [''Name'', ''TagName'', ''ClassName'', ''Selector'']
if type in list:
print(f"正在执行js操作:定位方式->{Type}, 元素值->{element}, 下标值->{index}, 执行操作->{action}")
if type == ''Selector'':
js = f''document.query{Type}All("{element}"){index}.{action}''
else:
js = f''document.getElementsBy{Type}({element})[{index}].{action};''
self.driver.execute_script(js)
else:
print(f"type参数 {Type} 错误,js定位仅可为:''Name''、''TagName''、''ClassName''、''Selector''(CSS)")

def js_readonly(self, idElement, value):
'''''' 去掉只读属性,并输入内容 一般为id ''''''
js = f''document.getElementById({idElement}).removeAttribute("readonly");document.getElementById({idElement}).value="{value}"''
driver.execute_script(js)

def js_iframe(self, Type, element, action, index=''''):
'''''' Js处理iframe 无需先切换到iframe上,再切回来操作
输入值:value='''' 点击:click() type=id时,index='''' ''''''
js = f''document.getElementBy{Type}({element}){index}.contentWindow.document.body.{action}''
driver.execute_script(js)
''''''
jquery = ''$(CSS).val("XXX");'' # 根据css语法定位到元素,输入内容
jquery = ''$(CSS).val('''');'' # 清空
jquery = ''$(CSS).click();'' # 点击
driver.execute_script(jquery)
''''''

# def switch_alert(self):
# '''''' 获取alert弹窗 ''''''
# r = self.is_alert()
# if not r:
# print("alert不存在")
# else:
# return r

# def is_title(self, title):
# ''''''判断当前title名为title 返回bool值''''''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_is(title))
# return result
# except:
# return False
# def is_title_contains(self, title):
# ''''''判断当前title名含title 返回bool值''''''
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.title_contains(title))
# return result
# except:
# return False

# def is_text_in_element(self, locator, _text=''''):
# ''''''判断当前获取到的text含_text='''' 返回bool值''''''
# if not isinstance(locator, tuple):
# print(''locator参数类型错误,必须传元祖类型:loc = ("id", "value1")'')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element(locator, _text))
# return result
# except:
# return False
# def is_value_in_element(self, locator, _value=''''):
# ''''''返回bool值, value为空字符串,返回False''''''
# if not isinstance(locator, tuple):
# print(''locator参数类型错误,必须传元祖类型:loc = ("id", "value1")'')
# try:
# result = WebDriverWait(self.driver, self.timeout, self.t).until(EC.text_to_be_present_in_element_value(locator, _value))
# return result
# except:
# return False

# def get_title(self):
# ''''''获取title''''''
# return self.driver.title
# def get_text(self, locator):
# ''''''获取文本''''''
# try:
# t = self.find(locator).text
# return t
# except:
# print("获取text失败,返回'''' ")
# return ""
# def get_attribute(self, locator, name):
# ''''''获取属性''''''
# try:
# element = self.find(locator)
# return element.get_attribute(name)
# except:
# print("获取%s属性失败,返回'''' "%name)
# return ""

# def select_by_index(self, locator, index=0):
# ''''''通过索引,index是索引第几个,从0开始,默认选第一个''''''
# element = self.find(locator) # 定位select这一栏
# Select(element).select_by_index(index)

# def select_by_value(self, locator, value):
# ''''''通过value属性''''''
# element = self.find(locator)
# Select(element).select_by_value(value)

# def select_by_text(self, locator, text):
# ''''''通过文本值定位''''''
# element = self.find(locator)
# Select(element).select_by_visible_text(text)

# def switch_handle_window_name(self, window_name):
# '''''' 根据句柄名字切换句柄 ''''''
# self.driver.switch_to.window(window_name)
# def switch_handle_index(self, index):
# '''''' 根据句柄下标切换句柄 ''''''
# handles = driver.window_handles
# self.driver.switch_to.window(handles[index])

# def js_find(self, action):
# ''''''
# 输入值:value=''XXX'' 点击:click()
# ''''''
# print("正在执行js操作,操作行为:%s"%action)
# js = "document.getElementById(“id”).%s"%action
# self.driver.execute_script(js)

if __name__ == "__main__":
driver = webdriver.Firefox()
driver.get("")
zentao = Base(driver)
# loc1 = (By.ID, "account")
# loc2 = (By.CSS_SELECTOR, "[name=''password'']")
# loc3 = (By.XPATH, "//*[@id=''submit'']")

loc1 = ("id", "account")
loc2 = ("css selector", "[name=''password'']")
loc3 = ("xpath", "//*[@id=''submit'']")
zentao.sendKeys(loc2, 123)

zentao.move_to_element(loc3)

今天关于selenium很多日志如何删除的分享就到这里,希望大家有所收获,若想了解更多关于c# – 是否可以在不安装Selenium Server的情况下使用ISelenium / DefaultSelenium?、java+selenium, python+selenium浏览界面,滑动页面、Python Selenium,如何删除元素?、python+selenium十:selenium的二次封装等相关知识,可以在本站进行查询。

本文标签: