一、截取页面图片

selenium可以对页面进行截图并保存。

web.save_screenshot("web1.png")

如果要把截下来的图片剪切要怎么做呢,虽然它不是selenium的内容。处理图片我们需要PIL这个模块 pip install Pillow 。然后确定图片对应的左上角和右下角的坐标。

例如,在百度页面截取这个图片:

python selenium 截图 指定区域 selenium指定位置截图_获取图片

 1.获取图片xpath路径

code_img_ele =  web.find_element_by_xpath('//*[@id="s_lg_img"]')

2.获取图片下x,y坐标

location = code_img_ele.location

3.获取图片对应的长和宽

size = code_img_ele.size

4.获取图片左上角和右下角坐标(前两个int是获取左上角,后两个是获取右下角)

rangle = (
    int(location['x']),int(location['y']),int(location['x'] + size['width']),int(location['y'] + size['height'])
)

5.开始剪切

i = Image.open('web1.png')
code_img_name = 'code.png'
frame = i.crop(rangle) #剪切
frame.save(code_img_name)#保存

完整代码:

import time
from selenium.webdriver import Chrome
from PIL import Image

web = Chrome()
time.sleep(3)
web.get("https://www.baidu.com/")
web.save_screenshot("web1.png")
code_img_ele =  web.find_element_by_xpath('//*[@id="s_lg_img"]')
location = code_img_ele.location
size = code_img_ele.size
rangle = (
    int(location['x']),int(location['y']),int(location['x'] + size['width']),int(location['y'] + size['height'])
)

i = Image.open('web1.png')
code_img_name = 'code.png'
frame = i.crop(rangle)
frame.save(code_img_name)

二、执行js操作

web.execute_script('js指令')

三、获取页面源代码(包含动态加载的内容)

page = web.page_source

四、动作链

导入动作链模块

from selenium.webdriver import  ActionChains

实例化对象:

action = ActionChains(浏览器对象)

使用动作链:

action.动作方法(要执行动作的目标).perform()

动作方法:

单击

click(self, on_element=None)

鼠标单击动作,输入参数为一个元素,可以不输入

单击并保持

click_and_hold(self, on_element=None)

鼠标点击一个元素并保持不放,参数为一个元素

右击

context_click(self, on_element=None)

右击一个元素,参数为一个元素

双击

double_click(self, on_element=None)

双击一个元素,参数为一个元素

拖放(将一个元素拖至另外一个元素)

drag_and_drop(self, source, target)

source元素拖放至target元素处,参数为两个元素

拖放(将一个元素拖放至另外一个位置)

drag_and_drop_by_offset(self, source, xoffset, yoffset)

将一个source元素拖放至xoffset, yoffset处,参数为一个元素,两个数值距离(需为整形)

按下某个按键

key_down(self, value, element=None)

按下某个按键如ctrl,shift,alt,参数为一个按键和一个元素(可为空)

松开一个按键

key_up(self, value, element=None)

松开某个按键如ctrl,shift,alt,参数为一个按键和一个元素(可为空)

移动鼠标一段横纵距离

move_by_offset(self, xoffset, yoffset)

移动鼠标至指定的坐标,参数为两个数值(需为整形)

移动至某个元素

move_to_element(self, to_element)

移动鼠标至一个指定的元素,参数为一个元素

松开鼠标

release(self, on_element=None)

方法为松开鼠标,和拖放等一起使用

键盘输入

send_keys(self, *keys_to_send)

向一个元素输入一个字符串,需先找到该元素

键盘输入

send_keys_to_element(self, element, *keys_to_send)

向一个元素输入一个字符串,参数为一个元素和一个字符串