4

python+selenium+phantomjs抓取ajax动态页面

 2 years ago
source link: https://www.hi-roy.com/posts/python-selenium-phantomjs%E6%8A%93%E5%8F%96ajax%E5%8A%A8%E6%80%81%E9%A1%B5%E9%9D%A2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python+selenium+phantomjs抓取ajax动态页面

2014-11-05

一般情况下,python爬虫遇到ajax动态页面一般都是直接分析后模拟ajax请求获得数据。不过今天遇到个网站,由于某些原因不透露网址了,点击搜索按钮后,它先跳转到a页面,然后从a页面跳转到b页面,再由b页面跳回a页面。当完成这2次跳转后,ajax向a页面提交的请求才会返回结果。

也怀疑是不是cookie或者refenen的问题,但最终证实不是因为这个。即便伪造了请求头再访问a页面,返回的也不是真实的结果页面而是一段跳转到b页面的js代码。

既然不知道跳转过程中网站到底干了写什么,那就直接上大杀器吧。

phantomjs可以简单的理解为js解释器,selenium更不用多介绍了,用pip安装即可。 从 http://phantomjs.org/download.html 下载编译后的包(当然你可以自己下源码),解压后的bin目录中就是我们需要的东西。

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
if __name__ == "__main__":
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.resourceTimeout"] = 5  # 超时
    dcap["phantomjs.page.settings.loadImages"] = False
    # 伪造ua信息
    dcap["phantomjs.page.settings.userAgent"] = ("myua")

    # 添加头文件
    # dcap["phantomjs.page.customHeaders.Referer"] = (
    #    "https://www.google.com/"
    #)
    # 代理
    service_args = [
        '--proxy=127.0.0.1:8080',
        #'--proxy-type=http',
        #'--proxy-type=socks5',
        #'--proxy-auth=username:password'
    ]
    driver = webdriver.PhantomJS(
         executable_path='./phantomjs',
         service_args=service_args,
         desired_capabilities=dcap
    )
    driver.get("http://www.xxx.cn/")
    driver.find_element_by_id('kw').send_keys("xxx") #模仿填写搜索内容
    driver.find_element_by_id("btn_ci").click() #模仿点击搜索按钮
    time.sleep(7)#等待页面加载
    page = driver.page_source
    open("res.html","w").write(page)
    driver.quit()

其中,我的源码直接放在了bin目录,所以executable_path直接指向当前目录,find_element_by_id这个查看目标网站源码就能知道,sleep的时间也要根据实际情况修改。这里也可以使用driver.implicitly_wait(30),不过这个网站的数据id都是随机生成的,所以我直接使用sleep了。

参考网站:

http://phantomjs.org/quick-start.html

http://blog.chinaunix.net/uid-22414998-id-3692113.html

http://blog.csdn.net/xiaoyao3857/article/details/9180989

https://realpython.com/blog/python/headless-selenium-testing-with-python-and-phantomjs/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK