什么是代理服務器
所謂代理服務器,是一個處于我們與互聯網中間的服務器,如果使用代
理服務器,我們瀏覽信息的時候,先向代理服務器發出請求,然后由代
理服務器向互聯網獲取信息,再返回給我們。
使用代理服務器進行爬取網頁實戰
使用代理服務器進行信息爬取,可以很好的解決IP限制的問題。
- 方法一
import urllib
# 39.82.135.164:8118
def useproxy(url,proxy_addr):
proxy = urllib.request.ProxyHandler({"http":proxy_addr})
opner = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
urllib.request.install_opener(opner) # 添加為全局
data = urllib.request.urlopen(url,timeout=5).read().decode("utf-8","ignore")
return data
print(useproxy("http://www.baidu.com","61.135.217.7:80"))
- 方法二
import urllib.request
def useproxy(url,proxy_addr):
proxy_handler = urllib.request.ProxyHandler({
'http': proxy_addr
})
opener = urllib.request.build_opener(proxy_handler)
data = opener.open(url).read().decode("utf-8","ignore")
return data
print(useproxy("http://www.baidu.com","61.135.217.7:80"))