您的位置:首页 > 运维架构 > 网站架构

利用phantomjs+selenium抓取fund.eastmoney.com/fund.html网站第二页js生成的页面

2017-11-21 09:45 736 查看
http://blog.csdn.net/github_26672553/article/details/78550623

前面我们了解过:利用
PyExecJS
包来执行js,然后直接拿到了基金网站第二页的字典数据。

现在和之前的不一样,我们利用
phantomjs
selenium
这2个包,模拟人工访问第二页,拿到第二页的网页源代码。



1、首先来肉眼分析第二页源码的特征。

用户点击”第二页”其实就是点击
value=2
的span元素。

当”第二页”加载了,span元素会多一个
at
的class。

2、找到”第二页”的按钮元素(也就是span),模拟点击

# coding: utf-8

from selenium import  webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

driver = webdriver.PhantomJS(executable_path=r"你phantomjs可执行文件绝对路径")

# 请求一个网址
driver.get("http://fund.eastmoney.com/fund.html")

# 得到点击js的span
pageBtn = driver.find_element_by_id("pager").find_element_by_xpath("span[@value=2]")
pageBtn.click()


3、判断是否已经是”第二页”了,我们需要自定义一个函数来完成

# 第二页的span元素是否有"at"这个class
def isAt(driver):
return driver.find_element_by_id("pager")\
.find_element_by_xpath("span[@value=2]")\
.get_attribute("class").find("at") != -1

WebDriverWait(driver,20).until(isAt)

print(driver.page_source) # 打印源码


最后打印源码确实是第二页的内容。

既然我们可以把第二页的网页内容抓取到,如何抓取第三页、第四页。。。

利用循环啊。

找到共有多少页,然后循环抓取就行了。

page_text = driver.find_element_by_id("pager").find_element_by_xpath("span[@class='nv']").text
total_page = ''.join(filter(str.isdigit,page_text)) # 得到总共有多少页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: