Python(四)IP代理

一、


import urllib2


if __name__ == '__main__' :

    

    url = 'http://www.baidu.com'

    proxy = {'http':'124.235.181.175:80'}

    proxy_support = urllib2.ProxyHandler(proxy)

    opener = urllib2.build_opener(proxy_support)

    opener.addheaders = [('User-Agent','Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19')]

    urllib2.install_opener(opener)    # 用install_opener將配置好的opener安裝到全局環境中,這樣所有的urllib2.urlopen都會自動使用代理

    response = urllib2.urlopen(url)

    html = response.read().decode('GBK')

    print html

   


二、


import urllib2


if __name__ == '__main__' :

    

    url = 'http://www.baidu.com'

    proxy = {'http':'124.235.181.175:80'}

    proxy_handler = urllib2.ProxyHandler(proxy)

    opener = urllib2.build_opener(proxy_handler)

    req = opener.open(url)   # 只有使用opener.open()方法發送請求才使用自定義的代理,而urlopen()則不使用自定義代理

    html = req.read().decode('utf-8')

    print html

    

三、

    

import urllib2

import random


if __name__ == '__main__' :

    

    url = 'http://www.baidu.com/'

    

    proxy_list = [

        {'http' : '124.88.67.81:80'},

        {'http' : '124.235.181.175:80'},

        {'http' : '123.53.134.254:8010'},

        {'http' : '61.135.217.7:80'},

        {'http' : '116.77.204.2:80'}

        ]

    proxy = random.choice(proxy_list)  # 隨機選擇一個代理


    proxy_handler = urllib2.ProxyHandler(proxy)  # 使用選擇的代理構建代理處理器對象


    opener = urllib2.build_opener(proxy_handler)

    opener.addheaders = [('User-Agent','Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19')]

    urllib2.install_opener(opener)


    req = urllib2.Request(url)

    response = urllib2.urlopen(req)

    html = response.read().decode('utf-8')

    print html


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