以北京大黃瓜為例,手把手教你使用scrapy抓取數(shù)據(jù)并存入MongoDB!
↑ 關(guān)注 + 星標(biāo) ,每天學(xué)Python新技能
后臺回復(fù)【大禮包】送你Python自學(xué)大禮包

目標(biāo)獲取



spider爬蟲


建立完畢結(jié)構(gòu)圖如下:


網(wǎng)頁分析

F12打開網(wǎng)頁源碼,如下這是一個POST請求的網(wǎng)頁,
分頁參數(shù)由limit控制,頁面顯示由current控制
并且每頁鏈接都是相同的,變化的只有分頁參數(shù)limit。
所以我們可以構(gòu)造一個請求url:
for page in range(1, 50+1):
url = f'http://www.xinfadi.com.cn/getPriceData.html?limit=20¤t={page}'

并且我們請求的數(shù)據(jù)是json結(jié)構(gòu),如下:
所有的內(nèi)容都在如下list列表中


發(fā)送請求

我們先來打印瀏覽器響應(yīng)數(shù)據(jù)
ic(response.text)
結(jié)果如下,成功打印出了json結(jié)構(gòu)的全部信息

但是我們需要的數(shù)據(jù)都在json結(jié)構(gòu)的list列表中,所以還需要對請求到的數(shù)據(jù)進(jìn)一步處理,獲取list
# 獲取蔬菜列表
veg_list = response.json()['list']
ic(veg_list)list結(jié)構(gòu)數(shù)據(jù)打印如下:

分析至此所有的信息都以獲取到,接下來我們要做的就是提取我們要獲取的數(shù)據(jù)
名稱、最低價、最高價、均價、產(chǎn)地還有價格發(fā)布時間等
for veg in veg_list:
# 實例化scrapy對象
item = BjXinfaItem()
# 蔬菜名稱
item['prodName'] = veg['prodName']
# 最低價格
item['lowPrice'] = veg['lowPrice']
# 最高價格
item['highPrice'] = veg['highPrice']
# 平均價格
item['avgPrice'] = veg['avgPrice']
# 產(chǎn)地
item['origin'] = veg['place']
# 日期
rlsDate = veg['pubDate']
item['rlsDate'] = ''.join(rlsDate).split(' ')[0]
'''
ic| item: {'avgPrice': '0.43',
'highPrice': '0.45',
'lowPrice': '0.4',
'origin': '冀',
'prodName': '大白菜',
'rlsDate': '2021-09-11'}
ic| item: {'avgPrice': '0.7',
'highPrice': '0.8',
'lowPrice': '0.6',
'origin': '冀',
'prodName': '娃娃菜',
'rlsDate': '2021-09-11'}
ic| item: {'avgPrice': '1.0',
'highPrice': '1.2',
'lowPrice': '0.8',
'origin': '',
'prodName': '小白菜',
'rlsDate': '2021-09-11'}
ic| item: {'avgPrice': '0.8',
'highPrice': '1.0',
'lowPrice': '0.6',
'origin': '冀',
'prodName': '圓白菜',
'rlsDate': '2021-09-11'}
ic| item: {'avgPrice': '0.65',
'highPrice': '0.7',
'lowPrice': '0.6',
'origin': '冀',
'prodName': '紫甘藍(lán)',
'rlsDate': '2021-09-11'}
ic| item: {'avgPrice': '1.2',
'highPrice': '1.5',
'lowPrice': '0.9',
'origin': '冀',
'prodName': '芹菜',
'rlsDate': '2021-09-11'}
'''

存入數(shù)據(jù)

當(dāng)我們要把數(shù)據(jù)保存成文件的時候,不需要任何額外的代碼,只要執(zhí)行如下代碼即可:
scrapy crawl spider爬蟲名 -o xxx.json #保存為JSON文件
scrapy crawl spider爬蟲名 -o xxx.jl或jsonlines #每個Item輸出一行json
scrapy crawl spider爬蟲名 -o xxx.csv #保存為csv文件
scrapy crawl spider爬蟲名 -o xxx.xml #保存為xml文件想要保存為什么格式的文件,只要修改后綴就可以了,在這里我就不一一例舉了。
我們在此將其保存為json格式
# 保存文件到本地
with open('./北京菜價.json', 'a+', encoding='utf-8') as f:
lines = json.dumps(dict(item), ensure_ascii=False) + '\n'
f.write(lines)每頁20條數(shù)據(jù),50頁攻擊1000條數(shù)據(jù)如下:


存入MongoDB

MongoDB的安裝之前專門拉出來一節(jié)單獨講的,需要的小伙伴可以看一下
Python也能操作MongoDB數(shù)據(jù)庫!
這里我們在setting中引入MongoDB。名稱如下:
mongo_host = '127.0.0.1'
mongo_port = 27017
mongo_db_name = 'beijing'
mongo_db_collection = 'beijing_price'數(shù)據(jù)查詢?nèi)缦拢?/span>

- END -
推薦閱讀
推薦一個公眾號,幫助程序員自學(xué)與成長
覺得還不錯就給我一個小小的鼓勵吧!


