首页 > 用selenium+phantomjs抓取异步加载的网页内容 为什么抓不到呢?

用selenium+phantomjs抓取异步加载的网页内容 为什么抓不到呢?

我要抓取如下网站的信息:http://www.cninfo.com.cn/information/companyinfo_n.html?fulltext?szcn300027,想获取里面所有文件的链接,然后下载下来。
这个网页时动态加载的,在源代码里面没有链接,所以我尝试用selenium+phantomjs的方法来获取内容,但是提示说找不到,想问问大家问题在哪儿?
代码如下:

# -*-coding:utf8 -*-

import requests
from selenium import webdriver
import time

class CninfInfo:
    def __init__(self):
        self.url = "http://www.cninfo.com.cn/cninfo-new/index"
        self.driver = webdriver.PhantomJS()

    def GetInfo(self):
        url = "http://www.cninfo.com.cn/information/companyinfo_n.html?fulltext?szcn300027"
        time.sleep(10)
        names = self.driver.find_elements_by_xpath("//ul[@class='ct-line']/li/div[@class='g3']/dd/span[@class='d1']/a")
        for name in names:
            print("名称为:",name.text)

if __name__ == "__main__":
    CI = CninfInfo()
    a = CI.GetInfo()

    

对于selenium不是很懂,但也玩过几次,可以看我的博客上的几篇文章,http://www.misitang.com。主要问题不是1楼所说的GET问题。而是它使用了一个iframe。需要先选定它,然后才能选中下面的元素。我用nodejs做了个示例,请自己看吧。

var webdriver = require('selenium-webdriver'),
    By = require('selenium-webdriver').By,
    until = require('selenium-webdriver').until;

var driver = new webdriver.Builder()
    .forBrowser('chrome')
    .build();

driver.get('http://www.cninfo.com.cn/information/companyinfo_n.html?fulltext?szcn300027');


driver.switchTo().frame('i_nr');
driver.findElements(By.css('span.d1>a')).then(fenxi);


function fenxi(ele){
    for(var e in ele){
        ele[e].getOuterHtml().then(function(oh)
        {
            console.log(oh);
        });
    }
}

目测没有调用 driver.get(url)


分页内容式是ajax请求局部刷新得到的,关于链接则是得到数据的参数拼接得到的,


  1. 首先输出完整的xml目录树,看看目录树中有没有你想要的数据

  2. 如果有再检查xpath代码有没有错误,如果目录树正确,可以尝试替换xpath代码为

//*[@id="ul_a_latest"]/li[2]/div[3]/dd[1]/span[1]/a

这仅仅是一个post提交,为什么要搞得这么复杂

import requests, json

url = 'http://www.cninfo.com.cn/cninfo-new/disclosure/szse/fulltext'
data = 'stock=300027&searchkey=&category=&pageNum=1&pageSize=15&column=szse_gem&tabName=latest&sortName=&sortType=&limit=&seDate='

headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
}

r = requests.post(url, data=data, headers=headers)
result = json.loads(r.text)

files = [_[0]['adjunctUrl'] for _ in result['classifiedAnnouncements']]

for file in files:
    file_url = 'http://www.cninfo.com.cn/{0}'.format(file)
    file_name = file.split('/')[2]
    with open(file_name, 'w') as f:
        f.write(requests.get(file_url).content)
【热门文章】
【热门文章】