最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何在Pycharm中制作自己的爬蟲(chóng)代碼模板

 更新時(shí)間:2021年12月29日 10:24:59   作者:lhys666  
當(dāng)有很多個(gè)個(gè)網(wǎng)站想要爬時(shí),每個(gè)爬蟲(chóng)的代碼不一樣,但有某種聯(lián)系,這個(gè)時(shí)候可以抽出一部分通用的代碼制成模板,減少代碼工作量。本文將具體介紹如何實(shí)現(xiàn)這一模板,需要的可以參考一下

寫(xiě)作背景

最近本菜雞有幾個(gè)網(wǎng)站想要爬,每個(gè)爬蟲(chóng)的代碼不一樣,但 有某種聯(lián)系,可以抽出一部分通用的代碼制成模板,減少代碼工作量,于是就有了這篇文章。

如果覺(jué)得我這篇文章寫(xiě)的好的話,能不能給我 點(diǎn)個(gè)贊 ,評(píng)論 、收藏 一條龍(☆▽☆)。如果要點(diǎn)個(gè) 關(guān)注 的話也不是不可以。

如果 有什么問(wèn)題,還 請(qǐng)各位大佬提出,不勝感激。

爬蟲(chóng)代碼

我的爬蟲(chóng)代碼都是使用的 自己 寫(xiě)的 多線程。

因?yàn)槲业拇a能力很差,所以如果代碼有哪里讓各位大佬倍感不適,請(qǐng)及時(shí)在評(píng)論區(qū) 指出,謝謝各位大佬。

我的代碼如下:

#!/usr/bin/python3
# -*- coding=utf-8 -*-
# @Author  : lhys
# @FileName: proxy_tool.py

import requests
import threading

timeout = 300
lock = threading.Lock()

# 請(qǐng)求頭用自己的
headers = {
    '': ''
}

class MyProxy:

    def __init__(self, proxy_api='', proxy_server='', max_use=5000, try_count=5):

        if not (proxy_api or proxy_server):
            raise TypeError('Proxy_api and proxy_server cannot be empty at the same time.')

        self.proxies = None if not proxy_server else {
            'http': proxy_server,
            'https': proxy_server
        }
        # 代理API
        self.proxy_api = proxy_api
        # 代理 IP 最大使用次數(shù)
        self.max_use = max_use
        # 測(cè)試代理 IP 次數(shù),超過(guò)次數(shù)即認(rèn)為代理 IP 不可用
        self.try_count = try_count
        # 是否爬蟲(chóng)請(qǐng)求出錯(cuò),如果出錯(cuò),直接更換 IP
        self.flag = 0
        # 代理 IP 剩余生存時(shí)間
        self.proxy_ttl = 0
        # 各種鎖
        self.lock = threading.Lock()
        self.ttl_lock = threading.Lock()
        self.flag_lock = threading.Lock()
    
    def set_flag(self):
        self.flag_lock.acquire()
        self.flag = 1
        self.flag_lock.release()

    def get_flag(self):
        self.flag_lock.acquire()
        flag = self.flag
        self.flag_lock.release()
        return flag

    def decrease_ttl(self):
        self.ttl_lock.acquire()
        self.proxy_ttl -= 1
        self.ttl_lock.release()

    def get_ttl(self):
        self.ttl_lock.acquire()
        ttl = self.proxy_ttl
        self.ttl_lock.release()
        return ttl

    def set_ttl(self):
        self.ttl_lock.acquire()
        self.proxy_ttl = self.max_use
        self.ttl_lock.release()

    def get_proxy(self):
        self.lock.acquire()
        proxy = self.proxies
        self.lock.release()
        return proxy

    def set_proxy(self):

        if self.proxy_ttl > 0 and self.flag == 0:
            return

        old = self.proxies

        if self.flag == 1:

            for try_count in range(self.try_count):

                try:
                    requests.get('https://www.baidu.com', headers=headers, proxies=old, timeout=timeout)
                    print(f'Test proxy {old} successfully.')
                    return

                except requests.exceptions.ProxyError or requests.exceptions.ConnectionError or requests.exceptions.ConnectTimeout:
                    print(f'Test proxy {old} failed.')
                    break

                except Exception as e:
                    print(e)

        if not self.proxy_api:
            raise ValueError('代理 IP 不可用,且代理 IP API未設(shè)置。')

        while True:

            res = requests.get(self.proxy_api)

            # 這一部分按照自己的代理 IP 文檔來(lái),僅供參考
            try:

                if res.json()["ERRORCODE"] == "0":

                    ip, port = res.json()["RESULT"][0]['ip'], res.json()["RESULT"][0]['port']

                    self.lock.acquire()

                    self.proxies = {
                        'http': 'http://%s:%s' % (ip, port),
                        'https': 'http://%s:%s' % (ip, port)
                    }

                    print(f'Set proxy: {ip}:{port}.')

                    self.flag = 0

                    self.lock.release()

                    self.set_ttl()

                    return

                else:
                    print(f'Set proxy failed.')

            except Exception as e:
                print(e)

Proxy = MyProxy()

def request_by_proxy(url, use_proxy=True):

    while True:

        try:
            # 使用代理
            if use_proxy:
            
                proxy_ttl = Proxy.get_ttl()
                print(proxy_ttl)
                
                # 如果 超過(guò)最大使用次數(shù) 或者 請(qǐng)求出現(xiàn)錯(cuò)誤,重新設(shè)置 IP
                if proxy_ttl <= 0 or Proxy.get_flag():
                    Proxy.set_proxy()

                print(Proxy.get_ttl())

                proxy = Proxy.get_proxy()

                lock.acquire()
                res = requests.get(url, headers=headers, proxies=proxy, timeout=timeout)
                lock.release()

                Proxy.decrease_ttl()

                return res

            else:

                res = requests.get(url, headers=headers, timeout=timeout)

                return res

        except requests.exceptions.ProxyError as pe:
            if use_proxy:
                lock.release()
            print(f'Proxy {Proxy.proxies} is not available, reason: {pe}.')
            Proxy.set_flag()

        except requests.exceptions.Timeout as t:
            if use_proxy:
                lock.release()
            print(f'Time out, reason: {t}.')
            Proxy.set_flag()

        except Exception as e:
            if use_proxy:
                lock.release()
            print(e)
#!/usr/bin/python3
# -*- coding=utf-8 -*-
# @Author  : lhys
# @FileName: spider.py

import time
import threading
from multiprocessing import Queue
from proxy_tool import request_by_proxy

threshold = 30
queue = Queue()

class Spider(threading.Thread):

    def __init__(self, use_proxy=True):
        super(Spider, self).__init__()
        self.use_proxy = use_proxy

    def get_data(self, url):

        try:

            res = request_by_proxy(url, self.use_proxy)
            
            # 響應(yīng)處理
            pass

        except Exception as e:

            print(e)

        return

    def run(self):

        while True:

            # 如果隊(duì)列空了,等待一會(huì)兒。
            # 過(guò)了指定的時(shí)間后,如果隊(duì)列出現(xiàn)數(shù)據(jù),就繼續(xù)爬
            # 如果隊(duì)列還是空的,停止線程

            if queue.empty():
                time.sleep(threshold)

            if not queue.empty():
                url = queue.get()
                self.get_data(url)
                time.sleep(threshold)

            else:
                print('Queue is empty.')
                return

在 Pycharm 中設(shè)置代碼模板

打開(kāi) File -> settings -> Editor -> Live Templates,點(diǎn)擊 Python,如下圖所示:

可以看到,已經(jīng)有一些自動(dòng)補(bǔ)全的模板了,以 TCP_Client 為例,如下圖所示:

可以看到 Pycharm 有提示。

使用 TCP_Client。

如果我們要制作自己的代碼模板,就點(diǎn)擊 + ,如下圖所示:

點(diǎn)擊 Live Template 。(第二個(gè)是 創(chuàng)建模板組,目前我們不需要,直接在 Python 模板組下創(chuàng)建就好了)。

其中:

  • Abbreviation 譯為 縮寫(xiě),就是 自動(dòng)補(bǔ)全框中出現(xiàn)的名字 。
  • Description 譯為 描述,就是 對(duì)這個(gè)代碼模板進(jìn)行描述,可空。
  • Template text 譯為 模板文本,就是 要設(shè)置的模板代碼。

然后在下方 define 處選擇在哪個(gè)模板組中定義,可 根據(jù)自己需求或喜好選擇模板組 ,我這里選擇 Python ,點(diǎn)擊 ok 。

測(cè)試一下:

成功完成任務(wù)!?。?/span>?

到此這篇關(guān)于如何在Pycharm中制作自己的爬蟲(chóng)代碼模板的文章就介紹到這了,更多相關(guān)Pycharm制作爬蟲(chóng)代碼模板內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python中with...as...的使用方法

    Python中with...as...的使用方法

    with是從Python2.5引入的一個(gè)新的語(yǔ)法,它是一種上下文管理協(xié)議,目的在于從流程圖中把 try,except 和finally 關(guān)鍵字和資源分配釋放相關(guān)代碼統(tǒng)統(tǒng)去掉,簡(jiǎn)化try….except….finlally的處理流程。具體內(nèi)容請(qǐng)看下面小編詳細(xì)的介紹
    2021-09-09
  • Python中staticmethod和classmethod的作用與區(qū)別

    Python中staticmethod和classmethod的作用與區(qū)別

    今天小編就為大家分享一篇關(guān)于Python中staticmethod和classmethod的作用與區(qū)別,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-10-10
  • Python統(tǒng)計(jì)列表元素出現(xiàn)次數(shù)的方法示例

    Python統(tǒng)計(jì)列表元素出現(xiàn)次數(shù)的方法示例

    這篇文章主要介紹了Python統(tǒng)計(jì)列表元素出現(xiàn)次數(shù)的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • python小白切忌亂用表達(dá)式

    python小白切忌亂用表達(dá)式

    在本篇內(nèi)容中小編給大家分享的是一篇關(guān)于python亂用表達(dá)式的新手問(wèn)題,需要的朋友們參考學(xué)習(xí)下吧。
    2020-05-05
  • Python獲取百度翻譯的兩種方法示例詳解

    Python獲取百度翻譯的兩種方法示例詳解

    本文介紹了使用Python通過(guò)requests和urllib兩種方式獲取百度翻譯的方法,requests方法通過(guò)發(fā)送post請(qǐng)求并解析json數(shù)據(jù),而urllib方法通過(guò)請(qǐng)求和讀取url來(lái)獲取翻譯,兩種方法各有優(yōu)劣,用戶可根據(jù)需求選擇
    2024-09-09
  • Python如何根據(jù)時(shí)間序列數(shù)據(jù)作圖

    Python如何根據(jù)時(shí)間序列數(shù)據(jù)作圖

    這篇文章主要介紹了Python如何根據(jù)時(shí)間序列數(shù)據(jù)作圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • django views重定向到帶參數(shù)的url

    django views重定向到帶參數(shù)的url

    這篇文章主要介紹了django views重定向到帶參數(shù)的url,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-03-03
  • python通過(guò)線程實(shí)現(xiàn)定時(shí)器timer的方法

    python通過(guò)線程實(shí)現(xiàn)定時(shí)器timer的方法

    這篇文章主要介紹了python通過(guò)線程實(shí)現(xiàn)定時(shí)器timer的方法,涉及Python線程與定時(shí)器timer的使用技巧,需要的朋友可以參考下
    2015-03-03
  • 一文詳解Python中Reduce函數(shù)輕松解決復(fù)雜數(shù)據(jù)聚合

    一文詳解Python中Reduce函數(shù)輕松解決復(fù)雜數(shù)據(jù)聚合

    這篇文章主要為大家介紹了Python中Reduce函數(shù)輕松解決復(fù)雜數(shù)據(jù)聚合示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • 淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法

    淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法

    這篇文章主要介紹了淺談Python使用pickle模塊序列化數(shù)據(jù)優(yōu)化代碼的方法,pickle模塊可以對(duì)多種Python對(duì)象進(jìn)行序列化和反序列化,序列化稱為pickling,反序列化稱為unpickling,需要的朋友可以參考下
    2023-07-07

最新評(píng)論

金昌市| 莱西市| 孙吴县| 德庆县| 鹿邑县| 山阴县| 安塞县| 巴彦县| 青河县| 滦平县| 上高县| 沙雅县| 哈尔滨市| 库伦旗| 普宁市| 平山县| 德庆县| 桃园县| 开鲁县| 陵川县| 江北区| 铜川市| 保亭| 芒康县| 芜湖县| 盖州市| 庆阳市| 区。| 衡阳市| 依兰县| 眉山市| 诸暨市| 镇雄县| 南丹县| 诏安县| 横山县| 东兴市| 岚皋县| 读书| 门源| 太湖县|