python - 用selenium+phantomjs抓取异步加载的网页内容 为什么抓不到呢?
黄舟
黄舟 2017-04-18 09:07:51
[Python讨论组]

我要抓取如下网站的信息: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/p[@class='g3']/dd/span[@class='d1']/a")
        for name in names:
            print("名称为:",name.text)

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

    
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(5)
怪我咯

这仅仅是一个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)
巴扎黑

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

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

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

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

对于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);
        });
    }
}
伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号