一、
創(chuàng)新互聯(lián)是一家專業(yè)從事成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、網(wǎng)頁設(shè)計(jì)的品牌網(wǎng)絡(luò)公司。如今是成都地區(qū)具影響力的網(wǎng)站設(shè)計(jì)公司,作為專業(yè)的成都網(wǎng)站建設(shè)公司,創(chuàng)新互聯(lián)依托強(qiáng)大的技術(shù)實(shí)力、以及多年的網(wǎng)站運(yùn)營經(jīng)驗(yàn),為您提供專業(yè)的成都網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)及網(wǎng)站設(shè)計(jì)開發(fā)服務(wù)!
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安裝到全局環(huán)境中,這樣所有的urllib2.urlopen都會(huì)自動(dòng)使用代理
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()方法發(fā)送請(qǐng)求才使用自定義的代理,而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) # 隨機(jī)選擇一個(gè)代理
proxy_handler = urllib2.ProxyHandler(proxy) # 使用選擇的代理構(gòu)建代理處理器對(duì)象
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