Python爬蟲入門教程 15-100 石家莊政民互動資料爬取
寫在前面
今天,咱抓取一個網站,這個網站呢,涉及的內容就是 網友留言和回覆,特別簡單,但是網站是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