溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python爬蟲(chóng)庫(kù)urllib2怎么用

發(fā)布時(shí)間:2020-08-24 18:06:54 來(lái)源:億速云 閱讀:187 作者:Leah 欄目:編程語(yǔ)言

本篇文章給大家分享的是有關(guān)Python爬蟲(chóng)庫(kù)urllib2怎么用,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。

所謂網(wǎng)頁(yè)抓取,就是把URL地址中指定的網(wǎng)絡(luò)資源從網(wǎng)絡(luò)流中讀取出來(lái),保存到本地。 在Python中有很多庫(kù)可以用來(lái)抓取網(wǎng)頁(yè),先學(xué)習(xí)urllib2。

urllib2模塊直接導(dǎo)入就可以用,在python3中urllib2被改為urllib.request

使用urllib2,試了下用代理登陸拉取cookie,跳轉(zhuǎn)抓圖片......

URLLIB2文檔:http://docs.python.org/library/urllib2.html

直接上demo代碼:包括:直接拉取,使用Reuqest(post/get),使用代理,cookie,跳轉(zhuǎn)處理

#!/usr/bin/python
# -*- coding:utf-8 -*-
# urllib2_test.py
import urllib,urllib2,cookielib,socket
url = "http://www.testurl....." #change yourself
#最簡(jiǎn)單方式
def use_urllib2():
 try:
  f = urllib2.urlopen(url, timeout=5).read()
 except urllib2.URLError, e:
  print e.reason
 print len(f)
#使用Request
def get_request():
 #可以設(shè)置超時(shí)
 socket.setdefaulttimeout(5)
 #可以加入?yún)?shù) [無(wú)參數(shù),使用get,以下這種方式,使用post]
 params = {"wd":"a","b":"2"}
 #可以加入請(qǐng)求頭信息,以便識(shí)別
 i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
       "Accept": "text/plain"}
 #use post,have some params post to server,if not support ,will throw exception
 #req = urllib2.Request(url, data=urllib.urlencode(params), headers=i_headers)
 req = urllib2.Request(url, headers=i_headers)
 #創(chuàng)建request后,還可以進(jìn)行其他添加,若是key重復(fù),后者生效
 #request.add_header('Accept','application/json')
 #可以指定提交方式
 #request.get_method = lambda: 'PUT'
 try:
  page = urllib2.urlopen(req)
  print len(page.read())
  #like get
  #url_params = urllib.urlencode({"a":"1", "b":"2"})
  #final_url = url + "?" + url_params
  #print final_url
  #data = urllib2.urlopen(final_url).read()
  #print "Method:get ", len(data)
 except urllib2.HTTPError, e:
  print "Error Code:", e.code
 except urllib2.URLError, e:
  print "Error Reason:", e.reason
def use_proxy():
 enable_proxy = False
 proxy_handler = urllib2.ProxyHandler({"http":"http://proxyurlXXXX.com:8080"})
 null_proxy_handler = urllib2.ProxyHandler({})
 if enable_proxy:
  opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler)
 else:
  opener = urllib2.build_opener(null_proxy_handler, urllib2.HTTPHandler)
 #此句設(shè)置urllib2的全局opener
 urllib2.install_opener(opener)
 content = urllib2.urlopen(url).read()
 print "proxy len:",len(content)
class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor):
 def http_error_403(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_400(self, req, fp, code, msg, hdrs):
  return fp
 def http_error_500(self, req, fp, code, msg, hdrs):
  return fp
def hand_cookie():
 cookie = cookielib.CookieJar()
 #cookie_handler = urllib2.HTTPCookieProcessor(cookie)
 #after add error exception handler
 cookie_handler = NoExceptionCookieProcesser(cookie)
 opener = urllib2.build_opener(cookie_handler, urllib2.HTTPHandler)
 url_login = "https://www.yourwebsite/?login"
 params = {"username":"user","password":"111111"}
 opener.open(url_login, urllib.urlencode(params))
 for item in cookie:
  print item.name,item.value
 #urllib2.install_opener(opener)
 #content = urllib2.urlopen(url).read()
 #print len(content)
#得到重定向 N 次以后最后頁(yè)面URL
def get_request_direct():
 import httplib
 httplib.HTTPConnection.debuglevel = 1
 request = urllib2.Request("http://www.google.com")
 request.add_header("Accept", "text/html,*/*")
 request.add_header("Connection", "Keep-Alive")
 opener = urllib2.build_opener()
 f = opener.open(request)
 print f.url
 print f.headers.dict
 print len(f.read())
if __name__ == "__main__":
 use_urllib2()
 get_request()
 get_request_direct()
 use_proxy()
 hand_cookie()

以上就是Python爬蟲(chóng)庫(kù)urllib2怎么用,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI