惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
G
Google Developers Blog
L
LangChain Blog
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
MyScale Blog
MyScale Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
Martin Fowler
Martin Fowler
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
V
V2EX

博客园 - Chen.HJ

python用正则对字符串进行运算 Nginx安装和遇到过的坑 Redis安装与常用命令 Nginx、Tomcat和Redis配置文件说明 python + selenium 获取标签文本的为空解决办法 Python读取Excel Python使用paramiko的SFTP get或put整个目录 Linux系统性能监控工具nmon python+selenium个人学习笔记11-登录封装与调用 python+selenium+unittest测试框架4-邮件发送最新测试报告 python+selenium+unittest测试框架3-项目构建和发送邮件 python+selenium+unittest测试框架2-装饰器@classmethod python+selenium+unittest测试框架1-unittest单元测试框架和断言 python+selenium个人学习笔记9-文件上传和cookie操作 python+selenium个人学习笔记8-获取信息和勾选框 python+selenium个人学习笔记7-警告框处理和下拉框选择 python+selenium个人学习笔记6-元素等待 python+selenium个人学习笔记5-多窗口和多表单切换 python+selenium个人学习笔记4-鼠标和键盘操作
python+selenium个人学习笔记10-调用JavaScript和截图
Chen.HJ · 2018-03-12 · via 博客园 - Chen.HJ

调用JavaScript和截图

一、调用JavaScript

1、调整浏览器滚动条位置

window.scrollTo(0,500); #左边距,上边距

2、用execute_script()执行JavaScript代码

js="window.scrollTo(0,500);"
driver.execute_script(js)

示例:

from selenium import webdriver
from time import sleep

driver=webdriver.Chrome()
driver.get("http://www.baidu.com")
driver.maximize_window()
driver.find_element_by_id("kw").send_keys("chen")
driver.find_element_by_id("su").click()
sleep(2)
# 通过javascript调整浏览器滚动条的位置
js="window.scrollTo(0,500);"
driver.execute_script(js)
sleep(3)
driver.quit()

PS:

1.滚动条回到顶部:
js="var q=document.getElementById('id').scrollTop=0"
driver.execute_script(js)
2.滚动条拉到底部
js="var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)

二、截图

1、截图

driver.get_screenshot_as_file()

示例:

from selenium import webdriver
from time import sleep

driver=webdriver.Chrome()
driver.get("http://www.baidu.com")
driver.maximize_window()
driver.find_element_by_id("kw").send_keys("chen")
driver.find_element_by_id("su").click()
sleep(2)
# 截取当前窗口并保存
driver.get_screenshot_as_file("E:\\chen.jpg")
driver.quit()