1. 程式人生 > >python爬蟲東方資料爬取

python爬蟲東方資料爬取

0.背景

1.分析網頁請求

開啟網頁,選擇某資料右鍵檢視元素,可以檢視該資料在載入後的網頁中的位置。 
這裡寫圖片描述
F12開啟開發者工具,開啟網頁檢視頁面請求,可以發現網頁傳送了多個請求,請求到的檔案包括html、css、js、png等,如下圖所示。 
這裡寫圖片描述
網頁主框架通過html請求載入,資料不在其中。資料是通過js單獨載入的。

2.方案介紹 
【方案一】 
BeautifulSoup解析網頁檔案。 
將網頁儲存在本地,python讀取後用BeautifulSoup解析獲得頁面資料。 
【方案二】 
selenium、PhantomJS、BeautifulSoup組合,通過模擬瀏覽器開啟對應網頁後用BeautifulSoup進行解析。

    from selenium import webdriver
    driver = webdriver.PhantomJS()
    jzc_html = "http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/GDZC/GetGDZC?tkn=eastmoney&cfg=gdzc&secucode=&fx=1&sharehdname=&pageSize=50&pageNum=1&sortFields=BDJZ&sortDirec=1&startDate=2017-11-29&endDate=2017-11-30"
driver.get(jzc_html) web_soup = BeautifulSoup(driver.page_source, "lxml") print web_soup.prettify()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

【方案三】 
前兩種方案對於獲取當前頁面資料還算比較有效,但對第二頁資料的獲取則束手無策。點選第二頁發現網頁只發送了一個請求資料的request,這就是資料介面啊。

http://data.eastmoney.com/DataCenter_V3/gdzjc.ashx?pagesize=50&page=2&js=var iTHPTzxw&param=&sortRule=-1
&sortType=BDJZ&tabid=jzc&code=&name=&rt=50406968
  • 1

用瀏覽器請求該網頁,發現返回值中包含了請求的資料和真實的資料介面。

"url":"http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/GDZC/GetGDZC?tkn=eastmoney&cfg=gdzc&secucode=&fx=1&sharehdname=&pageSize=50&pageNum=2&sortFields=BDJZ&sortDirec=1&startDate=&endDate="
  • 1

用瀏覽器請求該介面,正是我們需要的資料,用|分割。pageSize=50表每頁50條資料,pageNum=2表示當前請求的是第二頁。其他欄位容易理解。 
既然找到了資料介面,那就可以用urllib來請求,將響應的資料解析為json格式。

import urllib2
jzc_html = "http://datainterface3.eastmoney.com/EM_DataCenter_V3/api/GDZC/GetGDZC?" \
               "tkn=eastmoney&cfg=gdzc&secucode=&sharehdname=&pageSize=200&pageNum=1&sortFields=NOTICEDATE&sortDirec=1" \
               "&fx=2"\
               "&startDate="+start_data+"&endDate="+end_data
request = urllib2.Request(jzc_html)
response = urllib2.urlopen(request)
body = json.loads(response.read())
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

盡情的設定引數調戲介面吧,233