八、web爬蟲講解2—urllib庫爬蟲—ip代理—用戶代理和ip代理結合應用

百度雲搜索:http://bdy.lqkweb.com
搜網盤:http://www.swpan.cn
淘寶券:http://www.tbquan.cn

使用IP代理html

ProxyHandler()格式化IP,第一個參數,請求目標多是http或者https,對應設置
build_opener()初始化IP
install_opener()將代理IP設置成全局,當使用urlopen()請求時自動使用代理IPpython

#!/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代理池構建一web

適合IP存活時間長,穩定性好的代理ip,隨機調用列表裏的ipjson

#!/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代理池構建二,接口方式api

每次調用第三方接口動態獲取ip,適用於IP存活時間短的狀況瀏覽器

咱們用http://http.zhimaruanjian.com...dom

#!/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代理結合應用ide

#!/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)

【轉載自:https://www.jianshu.com/u/3fe...

相關文章
相關標籤/搜索