天天看點

8、web爬蟲講解2—urllib庫爬蟲—ip代理—使用者代理和ip代理結合應用

使用IP代理

ProxyHandler()格式化IP,第一個參數,請求目标可能是http或者https,對應設定

build_opener()初始化IP

install_opener()将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import urllib.request
import random   #引入随機子產品檔案

ip = "180.115.8.212:39109"
proxy = urllib.request.ProxyHandler({"https":ip})                        #格式化IP,注意:第一個參數可能是http或者https,對應設定
opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)  #初始化IP
urllib.request.install_opener(opener)       #将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP

#請求
url = "https://www.baidu.com/"
data = urllib.request.urlopen(url).read().decode("utf-8")
print(data)           

ip代理池建構一

适合IP存活時間長,穩定性好的代理ip,随機調用清單裡的ip

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib import request
import random   #引入随機子產品檔案
def dai_li_ip():
    ip = [
        '110.73.8.103:8123',
        '115.46.151.100:8123',
        '42.233.187.147:19'
        ]
    shui = random.choice(ip)
    print(shui)
    proxy = urllib.request.ProxyHandler({"https": shui})  # 格式化IP,注意,第一個參數,請求目标可能是http或者https,對應設定
    opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)  # 初始化IP
    urllib.request.install_opener(opener)  # 将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP

#請求
dai_li_ip() #執行代理IP函數
url = "https://www.baidu.com/"
data = urllib.request.urlopen(url).read().decode("utf-8")
print(data)           

ip代理池建構二,接口方式

每次調用第三方接口動态擷取ip,适用于IP存活時間短的情況

我們用

http://http.zhimaruanjian.com/

第三方接口測試

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib import request
import json
def dai_li_ip():
    url = "http://http-webapi.zhimaruanjian.com/getip?num=1&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1"
    data = urllib.request.urlopen(url).read().decode("utf-8")
    data2 = json.loads(data)  # 将字元串還原它本來的資料類型

    print(data2['data'][0])
    ip = str(data2['data'][0]['ip'])
    dkou = str(data2['data'][0]['port'])
    zh_ip = ip + ':' + dkou
    print(zh_ip)


    proxy = urllib.request.ProxyHandler({"https": zh_ip})  # 格式化IP,注意,第一個參數,請求目标可能是http或者https,對應設定
    opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)  # 初始化IP
    urllib.request.install_opener(opener)  # 将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP

#請求
dai_li_ip() #執行代理IP函數
url = "https://www.baidu.com/"
data = urllib.request.urlopen(url).read().decode("utf-8")
print(data)           

使用者代理和ip代理結合應用

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib import request
import json
import random
def yh_dl():    #建立使用者代理池
    yhdl = [
        'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
        'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
        'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
        'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
        'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
        'User-Agent:Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
        'Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
        'Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
        'Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10',
        'Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13',
        'Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)',
        'UCWEB7.0.2.37/28/999',
        'NOKIA5700/ UCWEB7.0.2.37/28/999',
        'Openwave/ UCWEB7.0.2.37/28/999',
        'Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999'
        ]
    thisua = random.choice(yhdl)                    #随機擷取代理資訊
    headers = ("User-Agent",thisua)                 #拼接報頭資訊
    opener = urllib.request.build_opener()          #建立請求對象
    opener.addheaders=[headers]                     #添加報頭到請求對象
    urllib.request.install_opener(opener)           #将報頭資訊設定為全局,urlopen()方法請求時也會自動添加報頭

def dai_li_ip():    #建立ip代理池
    url = "http://http-webapi.zhimaruanjian.com/getip?num=1&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1"
    data = urllib.request.urlopen(url).read().decode("utf-8")
    data2 = json.loads(data)  # 将字元串還原它本來的資料類型

    print(data2['data'][0])
    ip = str(data2['data'][0]['ip'])
    dkou = str(data2['data'][0]['port'])
    zh_ip = ip + ':' + dkou
    print(zh_ip)


    proxy = urllib.request.ProxyHandler({"https": zh_ip})  # 格式化IP,注意,第一個參數,請求目标可能是http或者https,對應設定
    opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)  # 初始化IP
    urllib.request.install_opener(opener)  # 将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP

#請求
dai_li_ip() #執行代理IP函數
yh_dl()     #執行使用者代理池函數

gjci = '連衣裙'
zh_gjci = gjc = urllib.request.quote(gjci)         #将關鍵詞轉碼成浏覽器認識的字元,預設網站不能是中文
url = "https://s.taobao.com/search?q=%s&s=0" %(zh_gjci)
# print(url)
data = urllib.request.urlopen(url).read().decode("utf-8")
print(data)           

使用者代理和ip代理結合應用封裝子產品

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib import request
import json
import random
import re
import urllib.error
def hq_html(hq_url):
    """
    hq_html()封裝的爬蟲函數,自動啟用了使用者代理和ip代理
    接收一個參數url,要爬取頁面的url,傳回html源碼
    """
    def yh_dl():    #建立使用者代理池
        yhdl = [
            'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
            'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
            'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
            'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
            'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11',
            'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)',
            'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
            'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
            'User-Agent:Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
            'Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5',
            'Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1',
            'Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10',
            'Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13',
            'Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+',
            'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)',
            'UCWEB7.0.2.37/28/999',
            'NOKIA5700/ UCWEB7.0.2.37/28/999',
            'Openwave/ UCWEB7.0.2.37/28/999',
            'Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999'
            ]
        thisua = random.choice(yhdl)                    #随機擷取代理資訊
        headers = ("User-Agent",thisua)                 #拼接報頭資訊
        opener = urllib.request.build_opener()          #建立請求對象
        opener.addheaders=[headers]                     #添加報頭到請求對象
        urllib.request.install_opener(opener)           #将報頭資訊設定為全局,urlopen()方法請求時也會自動添加報頭

    def dai_li_ip(hq_url):    #建立ip代理池
        url = "http://http-webapi.zhimaruanjian.com/getip?num=1&type=2&pro=&city=0&yys=0&port=11&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1"
        if url:
            data = urllib.request.urlopen(url).read().decode("utf-8")
            data2 = json.loads(data)  # 将字元串還原它本來的資料類型
            # print(data2['data'][0])
            ip = str(data2['data'][0]['ip'])
            dkou = str(data2['data'][0]['port'])
            zh_ip = ip + ':' + dkou
            pat = "(\w*):\w*"
            rst = re.compile(pat).findall(hq_url)  #正則比對擷取是http協定還是https協定
            rst2 = rst[0]
            proxy = urllib.request.ProxyHandler({rst2: zh_ip})  # 格式化IP,注意,第一個參數,請求目标可能是http或者https,對應設定
            opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)  # 初始化IP
            urllib.request.install_opener(opener)  # 将代理IP設定成全局,當使用urlopen()請求時自動使用代理IP
        else:
            pass

    #請求
    try:
        dai_li_ip(hq_url) #執行代理IP函數
        yh_dl()     #執行使用者代理池函數

        data = urllib.request.urlopen(hq_url).read().decode("utf-8")
        return data
    except urllib.error.URLError as e:  # 如果出現錯誤
        if hasattr(e, "code"):  # 如果有錯誤代碼
            # print(e.code)  # 列印錯誤代碼
            pass
        if hasattr(e, "reason"):  # 如果有錯誤資訊
            # print(e.reason)  # 列印錯誤資訊
            pass

# a = hq_html('http://www.baid.com/')
# print(a)           

子產品使用

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import fzhpach
gjc = '廣告錄音'
gjc = urllib.request.quote(gjc)                 #将關鍵詞轉碼成浏覽器認識的字元,預設網站不能是中文
url = 'https://www.baidu.com/s?wd=%s&pn=0' %(gjc)
a = fzhpach.hq_html(url)
print(a)           

【轉載自:

http://www.lqkweb.com

繼續閱讀