石家庄政民互動數據爬取-寫在前面
今天,咱抓取一個網站,這個網站呢,涉及的內容就是 網友留言和回復,特別簡單,但是網站是gov
的。網址為
http://www.sjz.gov.cn/col/1490066682000/index.html
首先聲明,為了學習,絕無惡意抓取信息,不管你信不信,數據我沒有長期存儲,預計存儲到重裝操作系統就刪除。
石家庄政民互動數據爬取-網頁分析
點擊更多回復 ,可以查看到相應的數據。
數據量很大14萬條,,數據爬完,還可以用來學習數據分析,真是nice
經過分析之后,找到了列表頁面。
數據的爬取這次我們采用的是 selenium
,解析頁面采用lxml
,數據存儲采用pymongo
,關於selenium
你可以去搜索引擎搜索相關的教程,好多的,主要就是打開一個瀏覽器,然后模擬用戶的操作,你可以去系統的學習一下。
石家庄政民互動數據爬取-擼代碼
導入必備模塊
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
import pymongo
import time
石家庄政民互動數據爬取-打開瀏覽器,獲取總頁碼
這個操作最重要的步驟,你搜索之后就會知道,需要提前下載一個叫做 chromedriver.exe 的東東,然后把他配置好,自行解決去吧~
# 加載瀏覽器引擎,需要提前下載好 chromedriver.exe 。
browser = webdriver.Chrome()
wait = WebDriverWait(browser,10)
def get_totle_page():
try:
# 瀏覽器跳轉
browser.get("http://www.sjz.gov.cn/zfxxinfolist.jsp?current=1&wid=1&cid=1259811582187")
# 等待元素加載到
totle_page = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,'input[type="hidden"]:nth-child(4)'))
)
# 獲取屬性
totle = totle_page.get_attribute('value')
# 獲取首頁數據,這個地方先不必須
##############################
#get_content()
##############################
return totle
except TimeoutError:
return get_totle_page()
上面的代碼在測試之后,你會得到如下結果
這時候,你已經得到20565
這個總頁碼數目了,只需要進行一系列循環的操作即可,接下來有一個重要的函數,叫做next_page
這個函數里面,需要進行一個模擬用戶行為的操作,輸入一個頁碼,然后點擊跳轉。
def main():
totle = int(get_totle_page()) # 獲取完整頁碼
for i in range(2,totle+1):
print("正在加載第{}頁數據".format(i))
# 獲取下一頁
next_page(i)
if __name__ == '__main__':
print(main())
輸入頁碼,點擊跳轉
def next_page(page_num):
try:
input = wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR,"#pageto"))
)
submit = wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR,"#goPage"))
)
input.clear() # 清空文本框
input.send_keys(page_num) # 發送頁碼
submit.click() # 點擊跳轉
#get_content(page_num)
except TimeoutException:
next_page(page_num)
以上代碼實現的效果動態演示為
石家庄政民互動數據爬取-解析頁面
可以進行翻頁之后,通過browser.page_source
獲取網頁源碼,網頁源碼通過lxml
進行解析。編寫相應的方法為
def get_content(page_num=None):
try:
wait.until(
EC.presence_of_element_located((By.CSS_SELECTOR, "table.tably"))
)
html = browser.page_source # 獲取網頁源碼
tree = etree.HTML(html) # 解析
tables = tree.xpath("//table[@class='tably']")
for table in tables:
name = table.xpath("tbody/tr[1]/td[1]/table/tbody/tr[1]/td")[0].text
public_time = table.xpath("tbody/tr[1]/td[1]/table/tbody/tr[2]/td")[0].text
to_people = table.xpath("tbody/tr[1]/td[1]/table/tbody/tr[3]/td")[0].text
content = table.xpath("tbody/tr[1]/td[2]/table/tbody/tr[1]/td")[0].text
repl_time = table.xpath("tbody/tr[2]/td[1]/table/tbody/tr[1]/td")[0].text
repl_depart = table.xpath("tbody/tr[2]/td[1]/table/tbody/tr[2]/td")[0].text
repl_content = table.xpath("tbody/tr[2]/td[2]/table/tbody/tr[1]/td")[0].text
# 清理數據
consult = {
"name":name.replace("網友:",""),
"public_time":public_time.replace("時間:",""),
"to_people":to_people.replace("留言對象:",""),
"content":content,
"repl_time":repl_time.replace("時間:",""),
"repl_depart":repl_depart.replace("回復部門:",""),
"repl_content":repl_content
}
# 數據存儲到mongo里面
#save_mongo(consult)
except Exception: # 這個地方需要特殊說明一下
print("異常錯誤X1")
print("瀏覽器休息一下")
time.sleep(60)
browser.get("http://www.sjz.gov.cn/zfxxinfolist.jsp?current={}&wid=1&cid=1259811582187".format(page_num))
get_content()
在實際的爬取過程中發現,經過幾百頁之后,就會限制一下IP,所以當我們捕獲頁面信息出錯,需要暫停一下,等待頁面正常之后,在繼續爬取數據。
數據存儲到mongodb里面
爬取到的最終數據,我存儲到了mongodb里面,這個就沒有什么難度了,我們按照常規的套路編寫即可。
寫在最后
由於這次爬取的網站是gov
的,所以建議不要用多線程,源碼也不發送到github上去了,要不惹禍,如果有任何疑問,請評論。nice boy
