自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

開發(fā) 后端
上周五,大師兄發(fā)給我一個網(wǎng)址,哭哭啼啼地求我:“去!把這個網(wǎng)頁上所有年所有縣所有作物的數(shù)據(jù)全爬下來,存到Access里!”我看他可憐,勉為其難地揮揮手說:“好嘞,馬上就開始!”

本節(jié)主要內(nèi)容有:

  • 通過requests庫模擬表單提交
  • 通過pandas庫提取網(wǎng)頁表格

上周五,大師兄發(fā)給我一個網(wǎng)址,哭哭啼啼地求我:“去!把這個網(wǎng)頁上所有年所有縣所有作物的數(shù)據(jù)全爬下來,存到Access里!”

我看他可憐,勉為其難地揮揮手說:“好嘞,馬上就開始!”

目標分析

大師兄給我的網(wǎng)址是這個:https://www.ctic.org/crm?tdsourcetag=s_pctim_aiomsg

打開長這樣:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

根據(jù)我學(xué)爬蟲并不久的經(jīng)驗,通常只要把年月日之類的參數(shù)附加到url里面去,然后用requests.get拿到response解析html就完了,所以這次應(yīng)該也差不多——除了要先想辦法獲得具體有哪些年份、地名、作物名稱,其他部分拿以前的代碼稍微改改就能用了,毫無挑戰(zhàn)性工作,生活真是太無聊了

點擊 View Summary 后出現(xiàn)目標網(wǎng)頁長這樣

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

那個大表格的數(shù)據(jù)就是目標數(shù)據(jù)了,好像沒什么了不起的——

有點不對勁

目標數(shù)據(jù)所在網(wǎng)頁的網(wǎng)址是這樣的:https://www.ctic.org/crm/?action=result ,剛剛選擇的那些參數(shù)并沒有作為url的參數(shù)啊!網(wǎng)址網(wǎng)頁都變了,所以也不是ajax

這和我想象的情況有巨大差別啊

嘗試獲取目標頁面

讓我來康康點擊View Summary這個按鈕時到底發(fā)生了啥:右鍵View Summary檢查是這樣:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

實話說,這是我第一次遇到要提交表單的活兒。以前可能是上天眷顧我,統(tǒng)統(tǒng)get就能搞定,今天終于讓我碰上一個post了。

點擊View Summary,到DevTools里找network第一條:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

不管三七二十一,post一下試試看

  1. import requests 
  2.   
  3. url = 'https://www.ctic.org/crm?tdsourcetag=s_pctim_aiomsg' 
  4. headers = {'user-agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 
  5.            'AppleWebKit/537.36 (KHTML, like Gecko) ' 
  6.            'Chrome/74.0.3729.131 Safari/537.36'
  7.            'Host''www.ctic.org'
  8. data = {'_csrf''SjFKLWxVVkkaSRBYQWYYCA1TMG8iYR8ReUYcSj04Jh4EBzIdBGwmLw=='
  9.         'CRMSearchForm[year]''2011'
  10.         'CRMSearchForm[format]''Acres'
  11.         'CRMSearchForm[area]''County'
  12.         'CRMSearchForm[region]''Midwest'
  13.         'CRMSearchForm[state]''IL'
  14.         'CRMSearchForm[county]''Adams'
  15.         'CRMSearchForm[crop_type]''All'
  16.         'summary''county'
  17. response = requests.post(url, data=data, headers=headers) 
  18. print(response.status_code) 

果不其然,輸出400……我猜這就是傳說中的cookies在搞鬼嗎?《Python3網(wǎng)絡(luò)爬蟲實戰(zhàn)》只看到第6章的我不禁有些心虛躍躍欲試呢!

首先,我搞不清cookies具體是啥,只知道它是用來維持會話的,應(yīng)該來自于第一次get,搞出來看看先:

  1. response1 = requests.get(url, headers=headers) 
  2. if response1.status_code == 200: 
  3.     cookies = response1.cookies 
  4.     print(cookies) 

輸出:

  1. <RequestsCookieJar[<Cookie PHPSESSID=52asgghnqsntitqd7c8dqesgh6 for www.ctic.org/>, <Cookie _csrf=2571c72a4ca9699915ea4037b967827150715252de98ea2173b162fa376bad33s%3A32%3A%22TAhjwgNo5ElZzV55k3DMeFoc5TWrEmXj%22%3B for www.ctic.org/>]> 

Nah,看不懂,不看不管,直接把它放到post里試試

  1. response2 = requests.post(url, data=data, headers=headers, cookies=cookies) 
  2. print(response2.status_code) 

還是400,氣氛突然變得有些焦灼,我給你cookies了啊,你還想要啥?!

突然,我發(fā)現(xiàn)一件事:post請求所帶的data中那個一開始就顯得很可疑的_csrf我仿佛在哪兒見過?

那個我完全看不懂的cookies里好像就有一個_csrf啊!但是兩個_csrf的值很明顯結(jié)構(gòu)不一樣,試了一下把data里的_csrf換成cookies里的_csrf確實也不行。

但是我逐漸有了一個想法:這個兩個_csrf雖然不相等,但是應(yīng)該是匹配的,我剛剛的data來自瀏覽器,cookies來自python程序,所以不匹配!

于是我又點開瀏覽器的DevTools,Ctrl+F搜索了一下,嘿嘿,發(fā)現(xiàn)了:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

這三處。

第一處那里的下一行的csrf_token很明顯就是post請求所帶的data里的_csrf,另外兩個是js里的函數(shù),雖然js沒好好學(xué)但也能看出來這倆是通過post請求獲得州名和縣名的,Binggo!一下子解決兩個問題。

為了驗證我的猜想,我打算先直接用requests獲取點擊View Summary前的頁面的HTML和cookies,將從HTML中提取的csrf_token值作為點擊View Summary時post請求的data里的_csrf值,同時附上cookies,這樣兩處_csrf就應(yīng)該是匹配的了:

  1. from lxml import etree 
  2. response1 = requests.get(url, headers=headers) 
  3. cookies = response1.cookies 
  4. html = etree.HTML(response1.text) 
  5. csrf_token = html.xpath('/html/head/meta[3]/@content')[0] 
  6. data.update({'_csrf': csrf_token}) 
  7. response2 = requests.post(url, data=data, headers=headers, cookies=cookies) 
  8. print(response2.status_code) 

輸出200,雖然和Chrome顯示的302不一樣,但是也表示成功,那就不管了。把response2.text寫入html文件打開看是這樣:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

Yeah,數(shù)據(jù)都在!說明我的猜想是對的!那一會再試試我從沒用過的requests.Session()維持會話,自動處理cookies。

嘗試pandas庫提取網(wǎng)頁表格

現(xiàn)在既然已經(jīng)拿到了目標頁面的HTML,那在獲取所有年、地區(qū)、州名、縣名之前,先測試一下pandas.read_html提取網(wǎng)頁表格的功能。

pandas.read_html這個函數(shù)時在寫代碼時IDE自動補全下拉列表里瞄到的,一直想試試來著,今天乘機拉出來溜溜:

  1. import pandas as pd 
  2. df = pd.read_html(response2.text)[0] 
  3. print(df) 

輸出:

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

Yeah!拿到了,確實比自己手寫提取方便,而且數(shù)值字符串自動轉(zhuǎn)成數(shù)值,優(yōu)秀!

準備所有參數(shù)

接下來要獲取所有年、地區(qū)、州名、縣名。年份和地區(qū)是寫死在HTML里的,直接xpath獲?。?/p>

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

州名、縣名根據(jù)之前發(fā)現(xiàn)的兩個js函數(shù),要用post請求來獲得,其中州名要根據(jù)地區(qū)名獲取,縣名要根據(jù)州名獲取,套兩層循環(huán)就行

  1. def new(): 
  2.     session = requests.Session() 
  3.     response = session.get(url=url, headers=headers) 
  4.     html = etree.HTML(response.text) 
  5.     return session, html 
  6.   
  7. session, html = new() 
  8. years = html.xpath('//*[@id="crmsearchform-year"]/option/text()'
  9. regions = html.xpath('//*[@id="crmsearchform-region"]/option/text()'
  10. _csrf = html.xpath('/html/head/meta[3]/@content')[0] 
  11. region_state = {} 
  12. state_county = {} 
  13. for region in regions: 
  14.     data = {'region': region, '_csrf': _csrf} 
  15.     response = session.post(url_state, data=data) 
  16.     html = etree.HTML(response.json()) 
  17.     region_state[region] = {x: y for x, y in 
  18.                             zip(html.xpath('//option/@value'), 
  19.                                 html.xpath('//option/text()'))} 
  20.     for state in region_state[region]: 
  21.         data = {'state': state, '_csrf': _csrf} 
  22.         response = session.post(url_county, data=data) 
  23.         html = etree.HTML(response.json()) 
  24.         state_county[state] = html.xpath('//option/@value'

嘖嘖,使用requests.Session就完全不需要自己管理cookies了,方便!具體獲得的州名縣名就不放出來了,實在太多了。然后把所有年、地區(qū)、州名、縣名的可能組合先整理成csv文件,一會直接從csv里讀取并構(gòu)造post請求的data字典:

  1. remain = [[str(year), str(region), str(state), str(county)] 
  2.          for year in years for region in regions 
  3.          for state in region_state[region] for county in state_county[state]] 
  4. remain = pd.DataFrame(remain, columns=['CRMSearchForm[year]'
  5.                                        'CRMSearchForm[region]'
  6.                                        'CRMSearchForm[state]'
  7.                                        'CRMSearchForm[county]']) 
  8. remain.to_csv('remain.csv'index=False
  9. # 由于州名有縮寫和全稱,也本地保存一份 
  10. import json 
  11. with open('region_state.json''w'as json_file: 
  12.         json.dump(region_state, json_file, indent=4) 

我看了一下,一共49473行——也就是說至少要發(fā)送49473個post請求才能爬完全部數(shù)據(jù),純手工獲取的話大概要點擊十倍這個數(shù)字的次數(shù)……

正式開始

那么開始爬咯

  1. import pyodbc 
  2. with open("region_state.json"as json_file: 
  3.     region_state = json.load(json_file) 
  4. data = pd.read_csv('remain.csv'
  5. # 讀取已經(jīng)爬取的 
  6. cnxn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' 
  7.                       'DBQ=./ctic_crm.accdb'
  8. crsr = cnxn.cursor() 
  9. crsr.execute('select Year_, Region, State, County from ctic_crm'
  10. done = crsr.fetchall() 
  11. done = [list(x) for x in done] 
  12. done = pd.DataFrame([list(x) for x in done], columns=['CRMSearchForm[year]'
  13.                                                       'CRMSearchForm[region]'
  14.                                                       'CRMSearchForm[state]'
  15.                                                       'CRMSearchForm[county]']) 
  16. done['CRMSearchForm[year]'] = done['CRMSearchForm[year]'].astype('int64'
  17. state2st = {y: x for z in region_state.values() for x, y in z.items()} 
  18. done['CRMSearchForm[state]'] = [state2st[x] 
  19.                                 for x in done['CRMSearchForm[state]']] 
  20. # 排除已經(jīng)爬取的 
  21. remain = data.append(done) 
  22. remain = remain.drop_duplicates(keep=False
  23. total = len(remain) 
  24. print(f'{total} left.n'
  25. del data 
  26.   
  27. # %% 
  28. remain['CRMSearchForm[year]'] = remain['CRMSearchForm[year]'].astype('str'
  29. columns = ['Crop'
  30.            'Total_Planted_Acres'
  31.            'Conservation_Tillage_No_Till'
  32.            'Conservation_Tillage_Ridge_Till'
  33.            'Conservation_Tillage_Mulch_Till'
  34.            'Conservation_Tillage_Total'
  35.            'Other_Tillage_Practices_Reduced_Till15_30_Residue'
  36.            'Other_Tillage_Practices_Conventional_Till0_15_Residue'
  37. fields = ['Year_''Units''Area''Region''State''County'] + columns 
  38. data = {'CRMSearchForm[format]''Acres'
  39.         'CRMSearchForm[area]''County'
  40.         'CRMSearchForm[crop_type]''All'
  41.         'summary''county'
  42. headers = {'user-agent''Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' 
  43.            'AppleWebKit/537.36 (KHTML, like Gecko) ' 
  44.            'Chrome/74.0.3729.131 Safari/537.36'
  45.            'Host''www.ctic.org'
  46.            'Upgrade-Insecure-Requests''1'
  47.            'DNT''1'
  48.            'Connection''keep-alive'
  49. url = 'https://www.ctic.org/crm?tdsourcetag=s_pctim_aiomsg' 
  50. headers2 = headers.copy() 
  51. headers2 = headers2.update({'Referer': url, 
  52.                             'Origin''https://www.ctic.org'}) 
  53. def new(): 
  54.     session = requests.Session() 
  55.     response = session.get(url=url, headers=headers) 
  56.     html = etree.HTML(response.text) 
  57.     _csrf = html.xpath('/html/head/meta[3]/@content')[0] 
  58.     return session, _csrf 
  59. session, _csrf = new() 
  60. for _, row in remain.iterrows(): 
  61.     temp = dict(row) 
  62.     data.update(temp
  63.     data.update({'_csrf': _csrf}) 
  64.     while True
  65.         try: 
  66.             response = session.post(url, data=data, headers=headers2, timeout=15) 
  67.             break 
  68.         except Exception as e: 
  69.             session.close() 
  70.             print(e) 
  71.             print('nSleep 30s.n'
  72.             time.sleep(30) 
  73.             session, _csrf = new() 
  74.             data.update({'_csrf': _csrf}) 
  75.   
  76.     df = pd.read_html(response.text)[0].dropna(how='all'
  77.     df.columns = columns 
  78.     df['Year_'] = int(temp['CRMSearchForm[year]']) 
  79.     df['Units'] = 'Acres' 
  80.     df['Area'] = 'County' 
  81.     df['Region'] = temp['CRMSearchForm[region]'
  82.     df['State'] = region_state[temp['CRMSearchForm[region]']][temp['CRMSearchForm[state]']] 
  83.     df['County'] = temp['CRMSearchForm[county]'
  84.     df = df.reindex(columns=fields) 
  85.     for record in df.itertuples(index=False): 
  86.         tuple_record = tuple(record) 
  87.         sql_insert = f'INSERT INTO ctic_crm VALUES {tuple_record}' 
  88.         sql_insert = sql_insert.replace(', nan,'', null,'
  89.         crsr.execute(sql_insert) 
  90.         crsr.commit() 
  91.     print(total, row.to_list()) 
  92.     total -= 1 
  93. else
  94.     print('Done!'
  95.     crsr.close() 
  96.     cnxn.close() 

注意中間有個try...except..語句,是因為不定時會發(fā)生Connection aborted的錯誤,有時9000次才斷一次,有時一次就斷,這也是我加上了讀取已經(jīng)爬取的和排除已經(jīng)爬取的原因,而且擔(dān)心被識別出爬蟲,把headers寫的豐富了一些(好像并沒有什么卵用),并且每次斷開都暫停個30s并重新開一個會話

 

Python模擬登錄實戰(zhàn),采集整站表格數(shù)據(jù)

然后把程序開著過了一個周末,命令行里終于打出了Done!,到Access里一看有816288條記錄,心想:下次試試多線程(進程)和代理池。

周一,我把跑出來的數(shù)據(jù)發(fā)給大師兄,大師兄回我:“好的”。

隔著屏幕我都能感受到滔滔不絕的敬仰和感激之情,一直到現(xiàn)在,大師兄都感動地說不出話來。

責(zé)任編輯:未麗燕 來源: 今日頭條
相關(guān)推薦

2020-11-06 08:28:44

Python

2016-08-18 00:35:39

Pythonwitte數(shù)據(jù)采集

2020-09-01 17:19:36

數(shù)據(jù)監(jiān)控建模

2021-08-02 12:29:15

Python爬蟲網(wǎng)站

2021-03-12 08:56:10

Java組件

2018-06-25 12:35:31

2011-06-18 04:07:21

2018-03-07 11:35:49

Python可視化數(shù)據(jù)

2021-09-11 09:07:17

Python驗證碼標注

2023-11-06 01:17:25

主機容器選項

2024-02-01 09:48:17

2021-12-17 12:12:22

Python 開發(fā)數(shù)據(jù)

2019-07-24 09:21:06

大數(shù)據(jù)采集采集系統(tǒng)大數(shù)據(jù)

2011-06-13 17:55:16

SEO

2009-11-20 14:48:07

2023-06-28 16:43:31

OCR數(shù)據(jù)管理

2010-09-09 10:07:05

DIVCSS

2020-08-16 12:44:59

小費數(shù)據(jù)集Python數(shù)據(jù)分析

2024-07-17 14:16:40

XMLPythonWeb開發(fā)

2023-11-29 10:16:24

ScrapyPython
點贊
收藏

51CTO技術(shù)棧公眾號