入手爬虫利器:phantomjs+selenium、自动填充文本框、自动点按钮

来源:互联网 发布:阿里云香港测试ip 编辑:程序博客网 时间:2024/05/20 14:17

这里写图片描述
http://fund.eastmoney.com/fund.html#os_0;isall_0;ft_;pt_1

前面我们通过『眼球』的方式,发现要抓取第二页的数据,是一段js脚本生成的。

我们希望能够启动获取到 第二页、第三页的脚本地址是什么?

phantomjs

好比是一个没有界面的浏览器内核,可以用它来执行脚本。隐形的执行css选择、DOM操作等。

官网地址:
http://phantomjs.org

下载之后解压,然后配置环境变量。

phantomjs -v

在终端下执行,如果正常输出就表示没有问题了。

下载之后解压,然后配置环境变量。

phantomjs -v

在终端下执行,如果正常输出就表示没有问题了。

代码测试一下phantomjs
在任意目录下新建一个test.js文件,代码如下:

console.log("hi,python");phantom.exit();

然后我们运行这个文件:

phantomjs test.js

不出意外正常输出了hi,python

到这里 ,是否觉得联想到了我们的node.js

selenium

selenium是一个web自动化测试框架,可以模拟一些人工操作,比如:点击按钮、输入文本、填充表单等。

https://seleniumhq.github.io/docs/

1、安装

#注意 还是要先cd我们python项目的虚拟环境下 #执行./python3 -m pip install selenium

selenium最终运行是需要驱动的,官方告诉我们使用chrome或者firefox等。
但是这不是我们想要的,我们这里需要的是前面安装的phantomjs

基本测试

# coding: utf-8from selenium import  webdriverdriver = webdriver.PhantomJS(executable_path=r"你phantomjs可执行文件的全路径")# 请求一个网址driver.get("http://www.baidu.com/")# 打印网页源码print(driver.title) # 百度一下,你就知道

ok,接下来我们来搜索一下python这个关键词,看看代码是怎么样的:

# coding: utf-8from selenium import  webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditionsdriver = webdriver.PhantomJS(executable_path=r"你的phantomjs可执行文件绝对路径")# 请求一个网址driver.get("http://www.baidu.com/")# 百度关键词输入框searchInput = driver.find_element_by_id("kw")# 我们来搜索一下 "python"这个关键字searchInput.send_keys("python")# 百度输入框提交按钮searchSubmitBtn = driver.find_element_by_id("su")searchSubmitBtn.submit() # 模拟提交表单# 因为百度的搜索是异步的# 我们这里设置等待20秒# 如果网页标题中包含了"python" 我们就认为加载成功了WebDriverWait(driver,20).until(expected_conditions.title_contains("python"))print(driver.title) # python_百度搜索

通过最后打印的标题,可以得知,我们搜索python已经成功了。