python-selenium development (1: basic usage)

Selenium is an automated testing tool for the web. It can locate specific web page elements through id/css/class/xpath and perform a series of operations to achieve automated testing!

Installation: pip install selenium

使用:
1.import selenium
2.from selenium import xxx

1. Install webdriver To
use selenium, you first need to install webdriver to connect to the browser and interact, so as to realize script control of the browser!
I installed it in both Google Chrome and Firefox:

Firefox browser webdriver download address
Google browser webdriver download address 1
Google browser webdriver download address 2
Google Chrome downloads first enter **chrome://version/** in the address bar before downloading, look at your own version and then download the corresponding
2 .Launch the browser:

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.baidu.com/')

The same goes for:

from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')

3. Positioning webpage elements The positioning of webpage elements
is the core of automated testing, and it is also the easiest place to step on. This place requires special attention! The usual ways to locate webpage elements are as follows:

1.id定位:find_element_by_id()
2.name定位:find_element_by_name()
3.class定位:find_element_by_class_name()
4.link定位:find_element_by_link_text()
5.partial link text定位:find_element_by_partial_link_text()
6.tag定位:find_element_by_tag_name()
7.xpath定位:find_element_by_xpath()
8.css定位:find_element_by_css_selector()

Some class names are composite classes with multiple class combinations, separated by spaces. If you use find_element_by_class_name(), the positioning will fail. In this case, you can use "." instead of spaces.
You can also use find_elements_by_xx to locate a group of elements

4. Selenium sets the waiting time.
Sometimes web content is cached or web page switching delays, etc., which will cause the next positioning element to fail, so you need to set the waiting time.
1. Forced waiting:

import time
time.sleep(x)

2. Display waiting
Explicitly wait to make WebdDriver continue to execute when a certain condition is satisfied, otherwise it will throw a timeout exception (TimeoutException) when the maximum duration is reached.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
element = WebDriverWait(driver, 5,0.5).until(EC.presence_of_element_located((By.ID, "kw")))
element.send_keys('selenium')
driver.quit()

The WebDriverWait class is
a wait method provided by WebDirver . During the set time, the default is to check whether the current page element exists every certain period of time. If it is not detected after the set time, an exception will be thrown. The specific format is as follows:
WebDriverWait(driver, timeout, poll_frequency=0.5,
ignored_exceptions=None)

  1. driver: browser driver.
  2. timeout: The longest timeout period, the default is in seconds.
  3. poll_frequency: detection interval (step length) time, the default is 0.5s.
  4. ignored_exceptions: exception information after timeout, NoSuchElementException is thrown by default.

WebDriverWait() is generally used in conjunction with the until() or until_not() methods. The following is the description of the until() and until_not() methods.
1.until(method, message='') Call the driver provided by this method as a parameter until the return value is True.
2. until_not(method, message='') Call the driver provided by this method as a parameter until the return value is False. In this example, the expected_conditions is renamed to EC by the as keyword, and the presence_of_element_located() method is called to determine whether the element exists.

3. Implicit wait

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import ctime
driver = webdriver.Firefox()
# 设置隐式等待为10秒
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")
try:
    print(ctime())  driver.find_element_by_id("kw22").send_keys('selenium')
except NoSuchElementException as e:
    print(e)
finally:
    print(ctime())
    driver.quit()

WebDriver provides an implicitly_wait() method to realize implicit wait, which is set to 0 by default.
The default parameter of implicitly_wait() is in seconds. In this example, the waiting time is set to 10 seconds.
First of all, this 10 seconds is not a fixed waiting time, it does not affect the execution speed of the script.
Second, it does not wait for an element on the page. When the script executes to a certain element location, if the element can be located, it will continue to execute; if the element cannot be located, it will continuously determine whether the element is located in a polling manner.
Assuming that the element is located in the 6th second, the execution continues. If the element is not located until the set time period (10 seconds) is exceeded, an exception will be thrown.
Invisible waiting is to set a maximum waiting time. If the web page is loaded within the specified time, execute the next step, otherwise wait until the time expires, and then execute the next step.

5. Control browser operation

function effect
driver.set_windows_size() Set the browser size (parameters are pixels)
driver.back() Back page
driver.forward() Forward page
driver.refresh() refresh page
driver.maximize_window() Maximize the page
driver.minimize_window() Minimize the page
from selenium import webdriver
driver = webdriver.Firefox()

#访问百度首页
first_url= 'http://www.baidu.com'
print("now access %s" %(first_url))
driver.get(first_url)
driver.maximize_window()
#访问新闻页面
second_url='http://news.baidu.com'
print("now access %s" %(second_url))
driver.get(second_url)

#返回(后退)到百度首页
print("back to  %s "%(first_url))
driver.back()

#前进到新闻页
print("forward to  %s"%(second_url))
driver.forward()

driver.quit()

7. Manipulate web page elements

method effect
click() Click element
clear() Clear text (if possible)
send_keys (value) Simulate key operation
get_attribute(name) Get element attribute value
is_displayed() Set whether the element is visible to the user
submit() submit Form
size Returns the size of the element
location Returns element coordinates
text Get the text of the element
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
#刷新浏览器
browser.refresh()

#提交表单
search_text = driver.find_element_by_id('kw')
search_text.send_keys('selenium')
search_text.submit()

# 获得输入框的尺寸
size = driver.find_element_by_id('kw').size
print(size)
loca=driver.find_element_by_id('kw').location
print(loca)

more_x = loca.get('x') #元素的x坐标
more_y = loca.get('y') #元素的y坐标
more_w = size.get('width')  #元素的宽
more_h = size.get('height') #元素的高

# 返回百度页面底部备案信息
text = driver.find_element_by_id("cp").text
print(text)

# 返回元素的属性值, 可以是 id、 name、 type 或其他任意属性
attribute = driver.find_element_by_id("kw").get_attribute('type')
print(attribute)

# 返回元素的结果是否可见, 返回结果为 True 或 False
result = driver.find_element_by_id("kw").is_displayed()
print(result)

driver.quit()

8. Mouse operation

In WebDriver, the mouse operation methods are encapsulated in the ActionChains class and provided.

from selenium.webdriver import ActionChains

Import the ActionChains class that provides mouse operations.

ActionChains(driver)

Call the ActionChains() class and pass in the browser driver as a parameter.
Commonly used functions:

function effect
double_click() Double click
drag_and_drop(source, target) Drag to an element and release
move_to_element(above) Hover over an element with the mouse
context_click() Simulate the right mouse button operation, you need to specify the positioning of the element when calling (right click)
perform() Executing all the actions stored in ActionChains can be understood as a submission action for the entire operation.
click(on_element=None) Click the left mouse button
move_by_offset(xoffset, yoffset) The mouse moves from the current position to a certain coordinate
drag_and_drop_by_offset(source, xoffset, yoffset) Drag to a certain coordinate and release
key_down(value, element=None) Press a key on a keyboard
key_up(value, element=None) Release a key
release(on_element=None) Release the left mouse button at an element position
send_keys_to_element(element, *keys_to_send) Send a key to the specified element
move_to_element_with_offset(to_element, xoffset, yoffset) How far to move to an element (upper-left coordinates)
from selenium import webdriver
# 引入 ActionChains 类
from selenium.webdriver.common.action_chains import ActionChains

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

# 定位到要悬停的元素
above = driver.find_element_by_link_text("设置")
# 对定位到的元素执行鼠标悬停操作
ActionChains(driver).move_to_element(above).perform()

9. Keyboard operation

function effect
send_keys(Keys.BACK_SPACE) Delete key (BackSpace)
send_keys(Keys.SPACE) Space
send_keys(Keys.TAB) Tab
send_keys(Keys.ESCAPE) Back key (Esc)
send_keys(Keys.ENTER) Enter
send_keys(Keys.CONTROL,‘a’) Select all (Ctrl+A)
send_keys(Keys.CONTROL,‘c’) Copy (Ctrl+C)
send_keys(Keys.CONTROL,‘x’) Cut (Ctrl+X)
send_keys(Keys.CONTROL,‘v’) 粘贴(Ctrl+V)
send_keys(Keys.F1) 键盘 F1
from selenium import webdriver
# 引入 Keys 模块
from selenium.webdriver.common.keys import Keys

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

# 输入框输入内容
driver.find_element_by_id("kw").send_keys("seleniumm")

# 删除多输入的一个 m
driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE)


# 输入空格键+“教程”
driver.find_element_by_id("kw").send_keys(Keys.SPACE)
driver.find_element_by_id("kw").send_keys("教程")

# ctrl+a 全选输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'a')

# ctrl+x 剪切输入框内容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'x')

# ctrl+v 粘贴内容到输入框
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'v')

# 通过回车键来代替单击操作
driver.find_element_by_id("su").send_keys(Keys.ENTER)
driver.quit()

10.获取断言信息
拿实际结果与预期进行比较,这个比较的称之为断言,通常通过获取title 、URL和text等信息进行断言。

title:用于获得当前页面的标题。

current_url:用户获得当前页面的URL。

text:获取搜索条目的文本信息。
from selenium import webdriver
from time import sleep


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

print('Before search================')

# 打印当前页面title
title = driver.title
print(title)

# 打印当前页面URL
now_url = driver.current_url
print(now_url)

driver.find_element_by_id("kw").send_keys("selenium")
driver.find_element_by_id("su").click()
sleep(1)

print('After search================')

# 再次打印当前页面title
title = driver.title
print(title)

# 打印当前页面URL
now_url = driver.current_url
print(now_url)

# 获取结果数目
user = driver.find_element_by_class_name('nums').text
print(user)

driver.quit()

运行结果如下:

Before search================
百度一下,你就知道
https://www.baidu.com/
After search================
selenium_百度搜索
https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx...
搜索工具
百度为您找到相关结果约5,380,000

Guess you like

Origin blog.csdn.net/liulanba/article/details/115294919