IP代理池的使用

參考書籍:python3網絡爬蟲開發與實戰     作者個人博客https://cuiqingcai.com/

下載IP代理池的程序,其作者放在了GitHubhttps://github.com/Python3WebSpider/ProxyPool

需要的工具:pycharm、各種庫、python37、redis安裝、redis可視化工具(在參考書籍作者博客中都有安裝方法)

1、下載IP代理池的安裝包,壓縮用pycharm打開點擊File->Open->選擇你剛下載的代理池的文件夾->New Window,等待片刻

2、點擊pycharm裏的命令行(Terminal),輸入python run.py,運行代碼,可以看到正在爬取ip

3、打開redis數據庫可視化工具,能看到爬取的ip存在數據庫中,在瀏覽器中輸入http://127.0.0.1:5555/random,可以打印出redis中的其中一個可用的IP

4、在pycharm中新創建一個.py文件,請求該http://127.0.0.1:5555/random,在下面圖中可以看到能打印出IP地址

5、現在我們用代理池的IP來請求我們需要的網址,運行過後可以看到IP地址是你數據庫中的IP地址,說明代理成功

import requests

PROXY_POOL_URL = 'http://localhost:5555/random'

def get_proxy():
    try:
        response = requests.get(PROXY_POOL_URL)
        if response.status_code == 200:
            return response.text
    except ConnectionError:
        return None

def get():
    proxy = get_proxy()
    proxies = {
        'http': 'http://' + proxy,
        'https': 'https://' + proxy
    }

    try:
        response = requests.get('http://httpbin.org/get', proxies=proxies)
        print(response.text)
    except requests.exceptions.ConnectionError as e:
        print('Error', e.args)

if __name__ == '__main__':
    get()

注意點:請求redis中的IP的時候,IP代理池不能關閉,如果關閉,則不會獲取到redis中的IP

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章