拾玖-Python 異步 爬蟲 MongoDB 等事宜實(shí)施

1. 綜述

根據(jù)前期的 NodeJS 代理池開展的爬蟲終于有所進(jìn)展奈揍,技術(shù)實(shí)現(xiàn)已初步實(shí)現(xiàn)绅项,相關(guān)引用資料如下所示:

2.代碼及注釋

'''
@Descripttion: 爬蟲測試頁面
@Author: BerryBC
@Date: 2020-01-30 15:00:34
@LastEditors  : BerryBC
@LastEditTime : 2020-01-31 13:53:19
'''
# 超時(shí)
# https://www.cnblogs.com/gl1573/p/10129382.html

# 爬蟲
# http://c.biancheng.net/view/2011.html

# 鏈接MongoDB
# https://blog.51cto.com/1767340368/2092960

# 異步處理
# https://blog.csdn.net/tinyzhao/article/details/52684473             //這不懂,做不了異步
# https://github.com/Blackyukun/IPProxyPool                           //這是有些代碼
# https://segmentfault.com/a/1190000008814676?utm_source=tag-newest   //這可以了
# https://www.cnblogs.com/shenh/p/9090586.html                        //最大并發(fā)數(shù)
# https://docs.aiohttp.org/en/stable/client_advanced.html             //沒啥事還是得去看官方文檔


# 引用庫
import requests
import time
import pymongo
from bs4 import BeautifulSoup
from target import arrTarget
import random
import time
import asyncio
import aiohttp

# 鏈接 MongoDB 的鏈接信息以及引用相關(guān)的表
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["dbProxy"]
mydb.authenticate('Berry', 'Berry')
mycol = mydb["tbProxy"]

# 讀取 MongoDB 中的代理信息
arrProxy = []
# 其中從數(shù)據(jù)庫中讀取 fail 次數(shù)小于等于8次的趁怔,只讀取 u 跟 p 字段湿硝,按 fail 倒序排序
for x in mycol.find({"fail": {"$lte": 8}}, {"_id": 0, "u": 1, "p": 1}).sort("fail", -1):
    arrProxy.append(x)

# 傳入給 aiohttp 用的信息
url = 'http://***.******.***/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
intProxyLen = len(arrProxy)

# 聲明拼死干活的函數(shù)
async def funSpyWeb(eleWeb, inSemaphore):
    # 限制并發(fā)數(shù)
    async with inSemaphore:
        bolRetry = True
        intTryTime = 0
        url = eleWeb
        try:
            async with aiohttp.ClientSession() as session:
                # 判斷是否需要重試以及是否所有代理均已用完
                while (bolRetry and (intTryTime < intProxyLen)):
                    try:
                        # 導(dǎo)入代理
                        real_proxy = "http://" + \
                            arrProxy[intTryTime]["u"] + \
                            ":"+arrProxy[intTryTime]["p"]
                        # 異步請求網(wǎng)頁內(nèi)容
                        async with session.get(url, proxy=real_proxy, timeout=5,headers=headers) as response:
                            # 如果成功了,這是測試润努,所以就暫時(shí)不管是否成功,只要不超時(shí)就行了
                            # if response.status == 200:
                            #     self._conn.put(proxy)
                            #     print('Valid proxy', proxy)
                            strhtml = await response.text()
                            # 列出所有鏈接示括,方便以后處理
                            soup = BeautifulSoup(strhtml, 'lxml')
                            data = soup.select('a')
                            # for item in data:
                            #     result = {
                            #         'title': item.get_text(),
                            #         'link': item.get('href')
                            #     }
                            #     print(result)
                            # 如果鏈接不超時(shí)即完成铺浇。
                            bolRetry = False
                            print("  After " + str(intTryTime) +
                                    " time, success reach " + url)
                            # print(data[0].get_text())
                    except Exception as e:
                        intTryTime += 1
                        # print('    Fail ' + str(intTryTime) + ' time')
        except Exception as e:
            print(e)

# 這里就只是調(diào)用而已,并且記錄開始結(jié)束時(shí)間
print('Begin : '+time.strftime('%Y-%m-%d %H:%M:%S'))
loop = asyncio.get_event_loop()
# 定義并發(fā)線程數(shù)
semaphore = asyncio.Semaphore(20)
# 把待爬 URL 放進(jìn)其中
waittask = asyncio.gather(
    *([funSpyWeb(strWebSite, semaphore) for strWebSite in arrTarget]))
loop.run_until_complete(waittask)
loop.close()
print('Program End : '+time.strftime('%Y-%m-%d %H:%M:%S'))


# --------- 以下不懂垛膝,失敗嘗試-------------
# class classSpy():
#     def __init__(self, arrInProxy):
#         self.arrProxy = iter(arrInProxy)

#     def __aiter__(self):
#         return self

#     async def __anext__(self):
#         try:
#             eleProxy = next(self.arrProxy)
#         except StopIteration:
#             raise StopAsyncIteration
#         return eleProxy
# arrTmp = []
# arrTmp.append(1)
# arrTmp.append(2)
# arrTmp.append(3)
# arrTmp.append(4)
# arrTmp.append(5)
# arrTmp.append(6)
# async def run():
#     print('Begin : '+time.strftime('%Y-%m-%d %H:%M:%S'))
#     async for eleBe in classSpy(arrTmp):
#         await asyncio.sleep(random.randint(1, 3))
#         print('  Now : ' + str(eleBe) + ' , time: ' +
#             time.strftime('%Y-%m-%d %H:%M:%S'))
#     print('End : '+time.strftime('%Y-%m-%d %H:%M:%S'))
# loop = asyncio.get_event_loop()
# loop.run_until_complete(run())
# ------------------------------------------


# --------- 以下為異步嘗試成功-------------
# arrTmp = []
# arrTmp.append(1)
# arrTmp.append(2)
# arrTmp.append(3)
# arrTmp.append(4)
# arrTmp.append(5)
# arrTmp.append(6)
# async def run(eleBe,inSemaphore):
#     async with inSemaphore:
#         await asyncio.sleep(random.randint(1, 3))
#         print('  Now : ' + str(eleBe) + ' , time: ' +
#             time.strftime('%Y-%m-%d %H:%M:%S'))
# def funDone(waittask):
#     print('Callback End : '+time.strftime('%Y-%m-%d %H:%M:%S'))
# print('Begin : '+time.strftime('%Y-%m-%d %H:%M:%S'))

# # -------------調(diào)用方式1----------------
# async def main():
#     semaphore=asyncio.Semaphore(2)
#     waittask =asyncio.gather (*( [run(proxy,semaphore) for proxy in arrTmp]))
#     waittask.add_done_callback(funDone)
#     await asyncio.gather(waittask)
# asyncio.run(main())
# # -------------------------------------


# # -------------調(diào)用方式2----------------
# loop = asyncio.get_event_loop()
# semaphore=asyncio.Semaphore(2)
# waittask =asyncio.gather (*( [run(proxy,semaphore) for proxy in arrTmp]))
# waittask.add_done_callback(funDone)
# loop.run_until_complete(waittask)
# loop.close()
# # -------------------------------------


# print('Program End : '+time.strftime('%Y-%m-%d %H:%M:%S'))
# ------------------------------------------

3.輸出結(jié)果

  ...
  After 2 time, success reach http://nx.cntour.cn/
  After 48 time, success reach http://www.cntour.cn/usercenter/default.aspx
  After 48 time, success reach http://bj.cntour.cn/
  After 48 time, success reach http://nmg.cntour.cn/
  After 48 time, success reach http://cntour.cn
  After 97 time, success reach http://sd.cntour.cn/
  After 97 time, success reach http://sh.cntour.cn/
  After 58 time, success reach http://sc.cntour.cn/
  After 58 time, success reach http://us.cntour.cn/
  After 21 time, success reach http://jp.cntour.cn/
  After 21 time, success reach http://www.cntour.cn/domestic/237/
  After 87 time, success reach http://mc.cntour.cn/
  ...

4.后續(xù)思考

其實(shí)主要做的當(dāng)然是把出來的 URL 放進(jìn)數(shù)據(jù)庫鳍侣,然后標(biāo)識時(shí)間,定期情理吼拥。
每次爬的都是少量倚聚,可以嘗試爬門戶網(wǎng)站或者社交網(wǎng)站等。
之后當(dāng)然要考慮爬相關(guān)網(wǎng)站時(shí)凿可,如何區(qū)分已爬信息跟未爬信息惑折,這個(gè)可能需要重點(diǎn)考慮或者考慮個(gè)性化授账。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市惨驶,隨后出現(xiàn)的幾起案子白热,更是在濱河造成了極大的恐慌,老刑警劉巖粗卜,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屋确,死亡現(xiàn)場離奇詭異,居然都是意外死亡续扔,警方通過查閱死者的電腦和手機(jī)攻臀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來纱昧,“玉大人刨啸,你說我怎么就攤上這事∑鲂” “怎么了呜投?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長存璃。 經(jīng)常有香客問我仑荐,道長,這世上最難降的妖魔是什么纵东? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任粘招,我火速辦了婚禮,結(jié)果婚禮上偎球,老公的妹妹穿的比我還像新娘洒扎。我一直安慰自己,他們只是感情好衰絮,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布袍冷。 她就那樣靜靜地躺著,像睡著了一般猫牡。 火紅的嫁衣襯著肌膚如雪胡诗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天淌友,我揣著相機(jī)與錄音煌恢,去河邊找鬼。 笑死震庭,一個(gè)胖子當(dāng)著我的面吹牛瑰抵,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播器联,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼二汛,長吁一口氣:“原來是場噩夢啊……” “哼婿崭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起习贫,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤逛球,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后苫昌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體颤绕,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年祟身,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了奥务。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡袜硫,死狀恐怖氯葬,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情婉陷,我是刑警寧澤帚称,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站秽澳,受9級特大地震影響闯睹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜担神,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一楼吃、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧妄讯,春花似錦孩锡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至炕置,卻和暖如春斩披,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背讹俊。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留煌抒,地道東北人仍劈。 一個(gè)月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像寡壮,于是被迫代替她去往敵國和親贩疙。 傳聞我的和親對象是個(gè)殘疾皇子讹弯,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評論 2 354

推薦閱讀更多精彩內(nèi)容