无法使用Python从HTML / Javascript中获取实际数据

时间:2017-08-17 09:05:46

标签: python-2.7 selenium splinter

我正在处理我的个人项目,我想存储那些时间又高又低的股票。

网站如下:

enter image description here

当我尝试获取HTML时,我得到了Javascripts,Jsons,因为页面正在逐字渲染。

我得到了这样的HTML:

function loadData(val){
    var url1 ; 
    if (val=='high'){
        url1 = '/products/dynaContent/equities/equities/json/online52NewHigh.json';
    }else{
        url1 = '/products/dynaContent/equities/equities/json/online52NewLow.json';
    }
    $.get(url1,
        function(data,curr){
             obj = eval('('+data+')');           

             maxPage= parseInt((obj.data.length)/ recordPerPage);

             if (((obj.data.length)%recordPerPage)>0){
                maxPage++;
             }
             setData(0);
        }
    );  
}

我不确定如何获取实际数据,我尝试了 selenium,splinter,urllib2 ,但在我的情况下不起作用。

代码:

from selenium import webdriver
from urllib2 import urlopen
import urllib2,cookielib

url = 'https://www.nseindia.com/products/content/equities/equities/eq_new_high_low.htm'
file_name = 'C:/Users/ASUS/Desktop/test.txt'


site= "https://www.nseindia.com/products/content/equities/equities/eq_new_high_low.htm"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

req = urllib2.Request(site, headers=hdr)


conn = urlopen(req)
data = conn.read()
conn.close()

file = open(file_name,'wt')
file.write(data)
file.close()

browser = webdriver.Firefox()
browser.get('file:///'+file_name)
html = browser.page_source
browser.quit()

我错过了什么吗?有没有其他方法可以在渲染后获取javascript / json数据?

1 个答案:

答案 0 :(得分:0)

当你有可浏览的JSON时,为什么要混合这么多东西?您的JSON路径已修复,因此请直接使用

from urllib2 import urlopen
import urllib2, cookielib
import json

url = "https://www.nseindia.com/products/dynaContent/equities/equities/json/online52NewHigh.json"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}
req = urllib2.Request(url, headers=hdr)

conn = urlopen(req)
data = conn.read()
conn.close()

data_json = json.loads(data)

print (data_json["data"][0]["symbol"])