《Python网络数据采集》第10章介绍了如何抓取JavaScript生成的页面的基本原理,同时也介绍了一下Xpath的语法,Xpath的一些语法,对于定位还是很有用的。
第10章内容简介:
1.先介绍了一下网页主要用的javascript库,jquery\Google Analytics\Google Map, 要抓取JavaScript生成的页面必须了解javascript库的基本运作。
2.接下来就是如何使用selenium( http://www.seleniumhq.org/),通过selenium模拟浏览器操作,然后读取页面内容。
selenium可以调用不同浏览器核心操作,文章中介绍主要还是使用phantomjs(http://phantomjs.org/)这个工具。
安装操作:
selenium安装:
pip install selenium
phantomjs下载解压即可,下载地址:https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2
建议加到PATH路径下
sudo ln -sf /pythontest/tool/phantomjs-2.1.1-linux-x86_64/bin/phantomjs /usr/local/bin/phantomjs
XPath语法简介:
selenium也支持XPath的定位方式(BeautifulSoup不支持)
XPath的一些语法比较有用,也列了一下:
:根节点和非根节点
—/div 根上的div节点
—//div 所有div节点
:定位属性
—//@href 所有href属性
—//a[@href='https://ask.hellobi.com/https://ask.hellobi.com'] 所有href指向天善的属性
:按位置选择
—//a[3] 第3个节点
—//table[last()] 最后的表格
—//a[position() < 3] 前3个表格
:通配符 (*)
—//table/tr/* 所有表格的所有内容
—//div[@*] div tag的所有属性
示例代码:
1-seleniumBasic.py
2-waitForLoad.py
3-javascriptRedirect.py
示例都比较简单,看一下就可以了。
不过里面有一点需要修改,我修改了一下示例1的代码,可以制定不同浏览器和具体的执行路径:
-------
#1-seleniumBasic.py
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path='')
#driver = webdriver.PhantomJS() #这个也可以
#driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')#这个也可以
driver.get("http://pythonscraping.com/pages/javascript/ajaxDemo.html")
time.sleep(3)
print(driver.find_element_by_id("content").text)
driver.close()