python - 用selenium+phantomjs抓取异步加载的网页内容 为什么抓不到呢?
本文介绍了python - 用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()
解决方案
这仅仅是一个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)
这篇关于python - 用selenium+phantomjs抓取异步加载的网页内容 为什么抓不到呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文