Python urllib、urllib2、httplib抓取網(wǎng)頁(yè)代碼實(shí)例
使用urllib2,太強(qiáng)大了
試了下用代理登陸拉取cookie,跳轉(zhuǎn)抓圖片......
文檔:http://docs.python.org/library/urllib2.html
直接上demo代碼了
包括:直接拉取,使用Reuqest(post/get),使用代理,cookie,跳轉(zhuǎn)處理
#!/usr/bin/python
# -*- coding:utf-8 -*-
# urllib2_test.py
# author: wklken
# 2012-03-17 wklken@yeah.net
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()
相關(guān)文章
Python實(shí)現(xiàn)返回?cái)?shù)組中第i小元素的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)返回?cái)?shù)組中第i小元素的方法,結(jié)合實(shí)例形式分析了Python針對(duì)數(shù)組的遍歷、排序、運(yùn)算等相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
使用PyInstaller將Python程序文件轉(zhuǎn)換為可執(zhí)行程序文件
與py2exe一樣,PyInstaller程序也可以將Python的.py程序文件轉(zhuǎn)換為.exe,并且還有Linux的版本,下面我們就來(lái)詳細(xì)看一下如何使用PyInstaller將Python程序文件轉(zhuǎn)換為可執(zhí)行程序文件2016-07-07
Python采用socket模擬TCP通訊的實(shí)現(xiàn)方法
這篇文章主要介紹了Python采用socket模擬TCP通訊的實(shí)現(xiàn)方法,程序分為T(mén)CP的server端與client端兩部分,分別對(duì)這兩部分進(jìn)行了較為深入的分析,需要的朋友可以參考下2014-11-11
python中出現(xiàn)invalid?syntax報(bào)錯(cuò)的幾種原因分析
這篇文章主要介紹了python中出現(xiàn)invalid?syntax報(bào)錯(cuò)的幾種原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
使用Python編寫(xiě)簡(jiǎn)單網(wǎng)絡(luò)爬蟲(chóng)抓取視頻下載資源
從上一篇文章的評(píng)論中看出似乎很多童鞋都比較關(guān)注爬蟲(chóng)的源代碼。所有本文就使用Python編寫(xiě)簡(jiǎn)單網(wǎng)絡(luò)爬蟲(chóng)抓取視頻下載資源做了很詳細(xì)的記錄,幾乎每一步都介紹給大家,希望對(duì)大家能有所幫助2014-11-11

