上周,有同事跟我說:“聽說你會寫Python,那能請你幫我寫個爬蟲嗎?”
之前雖然對爬蟲也僅僅停留在最基礎(chǔ)的地方,但是既然有這個機(jī)會,為什么不借著這個機(jī)會學(xué)習(xí)一下呢?于是就答應(yīng)了下來,開始了一周的爬坑之旅。
需要爬取的數(shù)據(jù)是國家統(tǒng)計局里的國家數(shù)據(jù),主要爬取固定資產(chǎn)與房地產(chǎn)兩個父指標(biāo)下,所有子指標(biāo)里所有省市自2013年以后的數(shù)據(jù)。(http://data.stats.gov.cn/easyquery.htm?cn=E0101)

使用瀏覽器自帶的開發(fā)者工具,觀察一下需要爬取的頁面,發(fā)現(xiàn)需要采集的數(shù)據(jù)是使用js生成的,這樣是無法通過requests直接獲取數(shù)據(jù)的。在這里我沒有去解析請求獲取數(shù)據(jù)的js代碼塊,而是采取了通過selenium模擬操作chrome瀏覽器,獲得渲染后的頁面,再使用beautifulsoup對源碼進(jìn)行解析,抓取需要的數(shù)據(jù)。
可能有小伙伴要問了,chrome是瀏覽器,這個不必多說;這selenium跟beautifulsoup是什么鬼?selenium其實是一款web自動測試工具,它可以模擬用戶的操作,在我們的例子里點(diǎn)擊按鈕靠的就是它,當(dāng)然它還有很多功能,在后面會提到;beautifulsoup是一個能從XML或HTML中提取數(shù)據(jù)的python庫,功能強(qiáng)大,使用簡單,是一款不可多得的好工具。
思路與使用的工具就先介紹到這,下面可以動手了!
首先引入需要使用的模塊:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from time import sleep
import pandas as pd
在這里需要說明一下,引入pandas是因為在網(wǎng)頁中每個省的數(shù)據(jù)是單獨(dú)展示的,需要在取完一個子指標(biāo)中所有數(shù)據(jù)后將所有省市的數(shù)據(jù)合并為一個文件,這時就需要用到pandas的concat方法了。
觀察一下我們需要爬取的頁面,其實省市以及父指標(biāo)子指標(biāo)都是固定的(這是國家統(tǒng)計的數(shù)據(jù),應(yīng)該不會隨意調(diào)整),這樣其實可以把需要爬取的數(shù)據(jù)的標(biāo)簽?zāi)贸鰜砥闯蓞?shù)列表(其實可以直接從頁面上抓取指定標(biāo)簽下的內(nèi)容,這里偷了個懶。。。)。不過這里需要注意的是,固定資產(chǎn)投資與房地產(chǎn)投資下的子指標(biāo)的標(biāo)簽id不是固定的,也是根據(jù)js生成的。
AREAS = ['110000', '120000', '130000', '140000', '150000', '210000','220000', '230000', '310000', '320000', '330000', '340000','350000', '360000', '370000', '410000', '420000', '430000','440000', '450000', '460000', '500000', '510000', '520000','530000', '540000', '610000', '620000', '630000', '640000','650000']
FATHERPOINTS = ['treeZhiBiao_6_a', 'treeZhiBiao_7_a']
SONPOINTS1 = ['treeZhiBiao_9', 'treeZhiBiao_10', 'treeZhiBiao_11']
SONPOINTS2 = ['treeZhiBiao_9', 'treeZhiBiao_10', 'treeZhiBiao_11']
tree1 = [FATHERPOINTS[0], SONPOINTS1, AREAS]
tree2 = [FATHERPOINTS[1], SONPOINTS2, AREAS]
TargetPath = [tree1, tree2]
接下來寫一個自動操作的方法:
def source_code(fatherPoint, sonPoint, areaCode):
#chrome設(shè)置為headless模式,也就是無界面瀏覽器。在window下需要同時設(shè)置--disable-gpu
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
#如果想要看到底是怎么模擬的,可以只使用webdriver.Chrome()
browser = webdriver.Chrome(chrome_options=chrome_options)
try:
#瀏覽器打開目標(biāo)url
browser.get('http://data.stats.gov.cn/easyquery.htm?cn=E0101')
#這里采用了一個顯式等待
locator = (By.XPATH, '//div[@class="mr-content"]')
WebDriverWait(browser, 20, 0.5).until(
EC.presence_of_element_located(locator))
#這里為啥要用一個強(qiáng)制等待呢?因為如果這里不加強(qiáng)制等待會找不到元素,也可能是我設(shè)置的有問題
sleep(1)
#點(diǎn)擊父指標(biāo)
browser.find_element(
By.XPATH, '//a[@id="{}"]'.format(fatherPoint)).click()
sleep(1)
#點(diǎn)擊子指標(biāo)
browser.find_element(
By.XPATH, '//li[@id="{}"]'.format(sonPoint)).click()
#點(diǎn)擊地區(qū)的下拉按鈕
browser.find_element(
By.XPATH, '//div[@id="mySelect_reg"]/div[@class="dtHtml"]/div[@class="dtHead"]').click()
#點(diǎn)擊需要查看的地區(qū)
browser.find_element(
By.XPATH, '//div[@id="mySelect_reg"]/div[@class="dtHtml"]/div[@class="dtBody"]/div[@class="dtList"]/ul/li[@code="{}"]'.format(areaCode)).click()
#點(diǎn)擊時間的下拉按鈕
browser.find_element(
By.XPATH, '//div[@id="mySelect_sj"]/div[@class="dtHtml"]/div[@class="dtHead"]').click()
#在指定時間的欄內(nèi)填入需要查詢的時間區(qū)間,并點(diǎn)擊確定
browser.find_element(
By.XPATH, '//div[@id="mySelect_sj"]/div[@class="dtHtml"]/div[@class="dtBody"]/div[@class="dtFoot"]/input[@class="dtText"]').send_keys("2013-2017")
browser.find_element(By.XPATH, '//div[@class="dtTextBtn"]').click()
#獲取渲染后的網(wǎng)頁代碼
sourceCode = browser.page_source
browser.quit()
return sourceCode
finally:
browser.quit()
然后再寫一個解析網(wǎng)頁的方法:
def annalysis_source_code(source_code, sonPoint):
#獲取當(dāng)前抓取父指標(biāo)的名稱作為文件名
global name
soup = BeautifulSoup(source_code, 'lxml')
region = soup.select(
'div[id="mySelect_reg"] > div[class="dtHtml"] > div[class="dtHead"]')[0].get_text()
print(region)
name = soup.select('li[id="{}"] > a'.format(sonPoint))[0].get("title")
headers = []
headerArr = soup.select(
'table[class="public_table table_fix"] > thead > tr[class="tr-title"] > th')
for i in headerArr:
headers.append(i.span['code'])
tables = []
rowArr = soup.select('table[class="public_table table_fix"] > tbody > tr')
for rowSoup in rowArr:
blocks = []
row = rowSoup.select('td')
for i in row:
blocks.append(i.get_text())
tables.append(blocks)
#創(chuàng)建dataframe,并轉(zhuǎn)置(因為爬下來的數(shù)據(jù)列名都是日期,轉(zhuǎn)置一下看起來比較數(shù)據(jù))
df = pd.DataFrame(tables, columns=headers)
df = df.T
columnName = df.ix['zb'].values.tolist()
df.columns = columnName
df = df.drop(['zb'])
df['region'] = region
return df
完整代碼請移步我的git項目:https://github.com/DeathShort/python-clawer-for-national-bureau-of-statistics