Python selenium的js扩展实现
python写的数据采集,对一般有规律的页面用 urllib2 + BeautifulSoup + 正则就可以搞定。 但是有些页面的内容是通过js生成,或者通过js跳转的,甚至js中还加入几道混淆机制;对这种涉及页面脚本解析的内容,前面的方式便很无力。
这时我们需要能解析、运行js的引擎——浏览器,而python selenium能提供程序与浏览器的交互接口,再加上phantomjs这个可以后台运行的浏览器,即使用 selenium + phantomjs 便可以解决以上的问题。
selenium可以操作页面的元素,并且提供执行js脚本的接口。但其调用js脚本后并不能直接返回执行的结果,这样再采集内容的过程中就会受到一些限制。 比如我们想使用页面中的函数进行数据转换,或者获取iframe里的内容,这些js产生数据要传回比较麻烦。
所以我便写一个简化js数据回传的扩展 exescript.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# created by heqingpan _init_js="""
(function (){
if (window.__e)
{ return;
}
var e=document.createElement('div');
e.setAttribute("id","__s_msg");
e.style.display="none";
document.body.appendChild(e);
window.__e=e;
})();
window.__s_set_msg=function(a){
window.__e.setAttribute("msg",a.toString()||"");
}
"""
_loadJsFmt="""
var script = document.createElement('script');
script.src = "{0}";
document.body.appendChild(script);
"""
_jquery_cdn="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"
_warpjsfmt="__s_set_msg({0})" class ExeJs(object):
def __init__(self,driver,trytimes=10):
from time import sleep
self.driver=driver
driver.execute_script(_init_js)
while trytimes >0:
try:
self.msgNode=driver.find_element_by_id('__s_msg')
break
except Exception:
sleep(1)
trytimes -= 1
if self.msgNode is None:
raise Exception()
def exeWrap(self,jsstr):
""" jsstr 执行后有返回值,返回值通过self.getMsg()获取 """
self.driver.execute_script(_warpjsfmt.format(jsstr))
def loadJs(self,path):
self.execute(_loadJsFmt.format(path))
def loadJquery(self,path=_jquery_cdn):
self.loadJs(path)
def execute(self,jsstr):
self.driver.execute_script(jsstr)
def getMsg(self):
return self.msgNode.get_attribute('msg')
打开ipython上一个例子,获取博客园首页文章title列表
from selenium import webdriver
import exescript d=webdriver.PhantomJS("phantomjs")
d.get("http://www.cnblogs.com/")
exejs=exescript.ExeJs(d)
exejs.exeWrap('$(".post_item").length')
print exejs.getMsg()
#out:
"""
20
""" jsstr="""(function(){
var r=[];
$(".post_item").each(function(){
var $this=$(this);
var $h3=$this.find("h3");
r.push($h3.text());
});
return r.join(',');})()"""
exejs.exeWrap(jsstr)
l=exejs.getMsg()
for title in l.split(','):
print title #out:
"""
mac TeamTalk开发点点滴滴之一——DDLogic框架分解上
The directfb backend was supported together with linux-fb backend in GTK+2.10
Science上发表的超赞聚类算法
功能齐全、效率一流的免费开源数据库导入导出工具(c#开发,支持SQL server、SQLite、ACCESS三种数据 库),每月借此处理数据5G以上
企业级应用框架(三)三层架构之数据访问层的改进以及测试DOM的发布
Unity3D 第一季 00 深入理解U3D开发平台
Welcome to Swift (苹果官方Swift文档初译与注解二十一)---140~147页(第三章--集合类型)
appium简明教程(11)——使用resource id定位
SQL语句汇总(终篇)—— 表联接与联接查询
fopen警告处理方式
AndroidWear开发之HelloWorld篇
AMD and CMD are dead之KMD.js版本0.0.2发布
SQL语句汇总(三)——聚合函数、分组、子查询及组合查询
DevExpress GridControl功能总结
ASP.NET之Jquery入门级别
2014年前端面试经历
grunt源码解析:整体运行机制&grunt-cli源码解析
跟用户沟通,问题尽量分析清楚,以及解决问题
ASP.NET之Ajax系列(一)
算法复杂度分析
"""
Python selenium的js扩展实现的更多相关文章
- python selenium --调用js
转自:http://www.cnblogs.com/fnng/p/3230768.html 本节重点: 调用js方法 execute_script(script, *args) 在当前窗口/框架 同步 ...
- python selenium处理JS只读(12306)
12306为例 js = "document.getElementById('train_date').removeAttribute('readonly');" driver.e ...
- 【Python + Selenium】之JS定位总结
感谢:小琰子 Python+Selenium 脚本中的一些js的用法汇总: 1.滚动条 driver.set_window_size(500,500) js = "window.scroll ...
- 使用Python + Selenium打造浏览器爬虫
Selenium 是一款强大的基于浏览器的开源自动化测试工具,最初由 Jason Huggins 于 2004 年在 ThoughtWorks 发起,它提供了一套简单易用的 API,模拟浏览器的各种操 ...
- 如何用python抓取js生成的数据 - SegmentFault
如何用python抓取js生成的数据 - SegmentFault 如何用python抓取js生成的数据 1赞 踩 收藏 想写一个爬虫,但是需要抓去的的数据是js生成的,在源代码里看不到,要怎么才能抓 ...
- Python+Selenium WebDriver API:浏览器及元素的常用函数及变量整理总结
由于网页自动化要操作浏览器以及浏览器页面元素,这里笔者就将浏览器及页面元素常用的函数及变量整理总结一下,以供读者在编写网页自动化测试时查阅. from selenium import webdrive ...
- python selenium+phantomjs alert()弹窗报错
问题:用selenium+phantomjs 模拟登陆,网页用JavaScript的alert("登陆成功")弹出框,但是用switch_to_alert().accept()报错 ...
- WEB自动化(Python+selenium)的API
在做Web自动化过程中,汇总了Python+selenium的API相关方法,给公司里的同事做了第二次培训,分享给大家 ...
- 利用 Python + Selenium 实现对页面的指定元素截图(可截长图元素)
对WebElement截图 WebDriver.Chrome自带的方法只能对当前窗口截屏,且不能指定特定元素.若是需要截取特定元素或是窗口超过了一屏,就只能另辟蹊径了. WebDriver.Phant ...
随机推荐
- Microsoft - Find the K closest points to the origin in a 2D plane
Find the K closest points to the origin in a 2D plane, given an array containing N points. 用 max hea ...
- JNI学习笔记_Java调用C —— Android中使用的方法
一.笔记 1.JNI(Java Native Interface),就是如何使用java去访问C/C++编写的那些库.若想深入了解JNI可以看官方文档jni.pdf.优秀博文:Android JNI知 ...
- ThinkPHP5 控制器中怎么实现 where id = 2 or id = 3 这个查询语句?
使用 whereOr whereIn(); (来自 ★C̶r̶a̶y̶o̶n-杭州 ) 为什么不用数组啊,array('eq', array(1,2),'or') (来自 supler)
- Ionic 中MD5加密使用
1. 下载安装ts-md5 在项目的命令行工具里输入 npm install ts-md5 --save 2. 使用 导入 import {Md5} from "ts-md5/dist/m ...
- [转]StarWind模拟iSCSI设备
StarWind模拟iSCSI设备 url: http://jimshu.blog.51cto.com/3171847/590412/ 标签:职场 iSCSI 休闲 StarWind 原创作品,允许 ...
- 锁定“嵌入式AI”应用 中科创达启动第二轮成长
Thundersoft|中科创达软件股份有限公司 http://www.thundersoft.com/index.php 原文:http://tech.hexun.com/2017-08-29/1 ...
- NSWindow添加NSViewController
大概这样,笔记一下,防止忘记 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { MyViewControl ...
- vim配置之目录结构
我喜欢作配置分离,这样比较好管理,这里直接贴一下tree的目录结构 xxx@debian:~/vimConfig$ tree . ├── install │ ├── install.sh │ ...
- press_keycode API 参数查询
用法 driver.press_ keycode(‘4’) 参数查找url:https://www.cnblogs.com/larack/p/4223465.html
- 5.验证用户名是否已经被注册:AJAXC请求
首先在 web.xml 文件中添加配置信息 <!-- 配置全局的字符集 --> <context-param> <param-name>encode</par ...