Selenium_ common methods

Element positioning is to locate the element you want to process. The common method is to do some operations on it, such as clicking, double-clicking, inputting content, etc.,
element positioning + common methods === UI automation

Basic common methods, special element positioning, frame operation, upload attachment operation, cookie operation, selenium help document

1. Basic method

1)send_Keys方法:模拟键盘输入
driver.find_element_by_id("kw").send_keys("python")2)text方法:获取你定位的文本
driver.find_element_by_link_text("新闻").text
(3)get_attribute();获取元素value属性的值
driver.find_element_by_id("su").get_attribute("value")4)maximize_window():浏览器窗口最大化
driver.maximize_window()5)current_window_handle:返回窗口句柄,意思就是标识窗口的字符串。
driver.current_window_handle
(6)current_url:获取当前窗口URL,
driver.current_url
(7)is_selected():判断是否被选择,如果多选框是被选中,则true
find_element_by_id("xx").is_selected()8)is_enabled():如果元素可用,则true
find_element_by_id("kw").is_enabled()9)is_displayed():如果元素在页面显示,则true
find_element_by_id("kw").is_displayed()10)clear():清空输入框
driver.find_element_by_id("kw").send_keys("python")
driver.find_element_by_id("kw").clear()11)quit():关闭浏览器并杀掉chromedriver.exe进程。不开这个,后台会有很多exe进程
(12)title:获取页面“title”,百度首页的title是“百度一下,你就知道”
driver.title
(13)refresh():刷新界面
driver.refresh()14)back():浏览器工具栏向后操作,比如:访问百度首页并后退到空页面:
#coding=utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.back()15)forward():浏览器工具栏向前操作,跟上面的相反,如下又跑到了百度网页
#coding=utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.back()
driver.forward()

2. Positioning of special elements
(1) In the mouse hovering operation
selenium, the keyboard and mouse are encapsulated in the action china class, mainly including single click, double click, drag and drop, etc.\

click() # 单击
click_and_hold()#单击并且按住不放
double_click()#双击
context_click()#右击
drag_and_drop(source,target)#拖拽
drag_and_drop(source,xoffset,yoffset)#将目标拖拽到目标位置
key_down(value,element=None)#按住某键,实现快捷操作
key_up()#松开某键
move_to_element(to_element)#将鼠标移动到某个元素上
move_to_element_with_offset(to_element,xoffset,yoffset)#移动到指定坐标
perform()#执行前面的一系列actionchains。
release()#释放按下的坐标

For reference, locate the settings, and after hovering the mouse,
locate the search settings and click

#coding=utf-8
from selenium import webdriver
from selenium.webdriver import ActionChains

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
bg_config = driver.find_element_by_id("s-usersetting-top")
ActionChains(driver).move_to_element(bg_config).perform()
driver.find_element_by_link_text("搜索设置").click()
driver.quit()

(2) Select operation
There are three types: select_by_index, select_by_value, select_by_visible_text. The third type is more used and has good maintainability. The first type is also good, and the second type is also good. I am accustomed to using the third type.

#coding=utf-8
from selenium import webdriver
from selenium.webdriver import ActionChains
import time
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
bg_config = driver.find_element_by_id("s-usersetting-top")
ActionChains(driver).move_to_element(bg_config).perform()
driver.find_element_by_link_text("搜索设置").click()
time.sleep(3)
# 定位到下拉框
se = driver.find_element_by_id('nr')
# 选择元素
Select(se).select_by_visible_text('每页显示20条')
driver.quit()

Three methods of processing return items (options):

# 返回选中的内容
ops = Select(se).all_selected_options
for i in ops:
    print(i.text)
# 返回所有的内容
ops = Select(se).options
for i in ops:
    print(i.text)
# 返回第一个被选中的选项
ops = Select(se).first_selected_option
for i in ops:
    print(i.text)

(3) Using javascript to manipulate page elements
webdriver does not directly support the controls on some browsers, such as the scroll bar on the right,
subtext , etc., but indirect operations with the help of js. Webdriver provides two types:
execute_script(): Synchronously execute code
execute_async_script(): Asynchronously execute code.
Insert picture description here
To enter selenium in the Baidu search box, the complete code is as follows:

#coding=utf-8
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.baidu.com/")
js = 'document.getElementById("kw").value="selenium"'
driver.execute_script(js)
driver.quit()

Use js to realize the operation of the browser scroll bar

#coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.set_window_size(800,700)
driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
js = "window.scrollTo(100,300)"
time.sleep(2)
driver.execute_script(js)
time.sleep(2)
driver.quit()

(4) jQuery operating page elements
jquery is a javascript class library, a powerful supplement to element positioning, which opens up the two veins of element positioning. You can refer to the jquery selector for details, but now there are more xpths. After you can copy the absolute path, it is really comfortable.

#coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.set_window_size(800,700)
jq = "$('#kw').val('selenium')"
driver.execute_script(jq)
time.sleep(2)
driver.quit()

(5) Commonly used keyboard events

Keys.BACK_SPACE #删除键
Keys.SPACE #空格键
Keys.TAB #TAB键
Keys.BACKSPACE #会推键
Keys.CONTROL,"a" #ctrl+a
Keys.CONTROL,"c" #ctrl+c
Keys.CONTROL,"v" #ctrl+v
Keys.CONTROL,"x" #ctrl+x
Keys.F1 #F1键
Keys.F12 #f12

Enter selenium and delete m

from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")

driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id('kw').send_keys(Keys.BACKSPACE)
# driver.find_element_by_id("kw").send_keys("selenium"+Keys.BACKSPACE)

driver.quit()

(5)
There are three types of frame tags for Frame operations : frameset, frame, and iframe. Frameset does not need to switch frames. Iframe and frame need to be switched inside this box to locate the element.
Log in to QQ mailbox as an example, as shown in the figure:

#coding=utf-8
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://mail.qq.com/")
driver.maximize_window()
driver.find_element_by_id('u').send_keys('test')
quit()

Error: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="u"]"}
Reason: Username embedded Set it in the iFrame frame, locate the element, and find that there was a frame in the previous time. The attribute value of the frame is id='login_frame'

After modification:
#coding=utf-8
from selenium import webdriver
import time
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://mail.qq.com/")
driver.maximize_window()
driver.switch_to.frame('login_frame')
driver.find_element_by_id('u').send_keys('test')
quit()
print('test finished')

Insert picture description here
If you want to locate outside the frame, return to the drive:

driver.switch_to.default_content()

Talk about several ways to position the frame:
(1) Positioning by index:

driver.switch_to.frame(0)0代表第一个frame

(2) Locate through the name attribute:

driver.switch_to.frame('login_frame')

(3) Positioning through webelement:

driver.switch_to.frame(driver.find_elements_by_id('login_frame'))

(6) When uploading attachments,
selenium itself cannot recognize windows. For example, there are three uploading methods: the
first is to
locate "add attachments"
Insert picture description here

If the element tag is input type and the type value is file, the code:
driver.find_element_by_name('UploadFile').send_keys('D:\\python\\chengdu.zip')

The second type:
With the help of the third-party library pywinauto, it is a tool library for interface operations, which specializes in handling widows GUI and can only be used in windows

from pywinatuo.applicaton import Application
# 定位到窗口
app = app.connect(title_re="打开",clsaa_name="#32770")
# 设置文件路径
app["打开"]["EDit1"].SetDditText("D:\soft\ip.txt")
time.sleep(2)
# 单击按钮
app["打开"]["Button1"].click()
print("end")

The third type:
realized with autoit, which is a tool for automated simulation of windows developed by basic language. Can interact with all standard widows controls, scripts can be turned into executable programs, easy to transplant, graphical interface can be created, and windows API functions can be called.
No introduction here, just focus on the second one.

(7) Cookie operation [not used much, the detailed content will be added later]
Selenium provides operations to read, add, and delete cookies
add_cookie(name)
delete_all_cookie()
delete_cookie(name)
get_cookie(name): return The cookie information named name
get_cookies(): returns all cookie information of the current session

(8) selenium help document
No

Guess you like

Origin blog.csdn.net/weixin_45451320/article/details/112503126