西刺代理python_python爬取西刺代理所有数据 !
今天來(lái)爬取西刺代理的所有數(shù)據(jù),采用 mongoDB 儲(chǔ)存。
首先分析網(wǎng)址構(gòu)造,找出規(guī)律,這里我們可以看到,總共有 3639 頁(yè)。
接著我們分析頁(yè)面源碼,通過正則來(lái)匹配出我們想要的數(shù)據(jù)。
正則調(diào)試:
for i in range(1,3640):
# 構(gòu)造 URL 地址
url='https://www.xicidaili.com/nn/'+str(i)
# 構(gòu)造 headers
headers={
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'
}
# 訪問該 URL 地址,獲取到頁(yè)面源碼
html=requests.get(url,headers=headers).text
# 構(gòu)造正則表達(dá)式
_retext=('
(.*?)[\s\S]*?(.*?)[\s\S]*?'+'(.*?)[\s\S]*?(.*?)'
+'[\s\S]*?
(.*?)[\s\S]*?(.*?)'+'
[\s\S]*?(.*?)')# 正則匹配出頁(yè)面中的數(shù)據(jù)
content=re.findall(_retext,html)
獲取到數(shù)據(jù)以后,我們連接 mongoDB。
# 連接mongoDB
client=pymongo.MongoClient(host='localhost',port=27017)
# 打開‘xicidata’,如果不存在則創(chuàng)建
db=client['xicidata']
# 創(chuàng)建 ‘data’ 表
t1=db['data']
接著把數(shù)據(jù)寫入表‘data’中
for j in content:
# 通過for,把獲取到的數(shù)據(jù)放到dict中
_data={'IP地址':j[0],
'port':j[1],
'adresse':j[2],
'N':j[3],
'type':j[4],
'cunhuo':j[5],
'time':j[6]
}
# 把 dict 插入到表中
t1.insert_one(_data)
print('writing...')
最后,我們貼出全部代碼
import requests
import re
import pymongo
from time import sleep
# 連接mongoDB
client=pymongo.MongoClient(host='localhost',port=27017)
# 打開‘xicidata’,如果不存在則創(chuàng)建
db=client['xicidata']
# 創(chuàng)建 ‘data’ 表
t1=db['data']
for i in range(1,3640):
# 構(gòu)造 URL 地址
url='https://www.xicidaili.com/nn/'+str(i)
# 構(gòu)造 headers
headers={
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'
}
# 訪問該 URL 地址,獲取到頁(yè)面源碼
html=requests.get(url,headers=headers).text
sleep(5)
# 構(gòu)造正則表達(dá)式
_retext=('
(.*?)[\s\S]*?(.*?)[\s\S]*?'+'(.*?)[\s\S]*?(.*?)'
+'[\s\S]*?
(.*?)[\s\S]*?(.*?)'+'
[\s\S]*?(.*?)')# 正則匹配出頁(yè)面中的數(shù)據(jù)
content=re.findall(_retext,html)
# 迭代出數(shù)據(jù)
for j in content:
# 通過for,把獲取到的數(shù)據(jù)放到dict中
_data={'IP地址':j[0],
'port':j[1],
'adresse':j[2],
'N':j[3],
'type':j[4],
'cunhuo':j[5],
'time':j[6]
}
# 把 dict 插入到表中
t1.insert_one(_data)
print('writing...')
通過 pycharm 的插件,我們看到,mongoDB成功創(chuàng)建了庫(kù)‘xicidata’,該庫(kù)下成功創(chuàng)建了表‘data’。
數(shù)據(jù)寫入成功!
總結(jié)
以上是生活随笔為你收集整理的西刺代理python_python爬取西刺代理所有数据 !的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HALCON示例程序inner_rect
- 下一篇: 【Hadoop系列】HDFS