python抓取資料,python使用socks代理抓取資料

來源:互聯網
上載者:User

標籤:host   科技   width   python   pip   bsp   steam   get   uil   

  在python中,正常的抓取資料直接使用urllib2 這個模組:

import urllib2url = ‘http://fanyi.baidu.com/‘stream = urllib2.urlopen(url)cont = stream.read()print cont

  如果要走http代理的話,我們也可以使用urllib2,不需要引用別的模組:

import urllib2url = ‘https://clients5.google.com/pagead/drt/dn/dn.js‘proxy_handler = urllib2.ProxyHandler({‘http‘:‘127.0.0.1:1080‘})opener = urllib2.build_opener(proxy_handler)f = opener.open(url)print f.read()

  如果要使用socks5代理, 我們需要別的模組 sockes, socket, 我們可以通過pip install socksipy , (我是windows的系統, 還需要另外的一個模組, pip install win_inet_pton) 建議直接下載安裝包到python的安裝目錄,切換到對應目錄,執行python setup.py install安裝,真被大天朝的牆給坑死了, 然後在需要代理的模組上添加socket代碼:

import socksimport socketsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1080)socket.socket = socks.socksocket

  完整的代碼如下:

//添加的代碼開頭
import win_inet_ptonimport socksimport socketsocks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 1080)socket.socket = socks.socksocket
//添加的代碼結束import urllib2steam = urllib2.urlopen(‘https://clients5.google.com/pagead/drt/dn/dn.js‘)print steam.read()

  使用requests模組, 我們也在requests之前添加socket的代碼,後面的http請求不用改了,還是走原來的邏輯:

//添加的代碼開頭
import win_inet_ptonimport socketimport socksimport requestsip=‘localhost‘port = 1080socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, ip, port)socket.socket = socks.socksocket//添加的代碼結束
url = ‘https://clients5.google.com/pagead/drt/dn/dn.js‘print requests.get(url).text

  相關:

  github:https://github.com/mitsuhiko/python-geoip/issues/4

NONO
出處:http://www.cnblogs.com/diligenceday/
企業網站:http://www.idrwl.com/ 廈門點燃未來網路科技
開源部落格:http://www.github.com/sqqihao
QQ:287101329
:18101055830 

廈門點燃未來網路科技有限公司, 是廈門最好的應用, 小程式, 網站, 公眾號開發公司

python抓取資料,python使用socks代理抓取資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.