0X00 簡介
urlopen是urllib的的一個方法,它屬於類文件對象,具有文件對象的方法,如read()等,同時也具有自身的一些方法:
1、info() 返回響應包的頭信息
2、info().getheader() 返回頭信息中指定內容,如Content-Type值等
2、getcode() 返回響應碼,如200表示可以訪問,404表示無法訪問
3、geturl 返回請求的url地址
0X01 作用
1、獲取服務器返回的header內容
#coding:utf-8 import urllib header=urllib.urlopen('http://www.baidu.com').info() print header print header.info().getheader('Content-Type')
2、獲取服務器返回的body內容
#coding:utf-8 import urllib import urllib2 url='http://127.0.0.1/sqli-labs-master/Less-15/' req=urllib2.Request(url) #創建請求對象 values={'uname':'admin','passwd':'admin'} #請求的post數據 data=urllib.urlencode(values) #對post數據進行url編碼 resp=urllib2.urlopen(req,data).read() #讀取響應對象內容,將其賦值給resp with open('data.txt','a') as fw: for line in resp: fw.write(line) #將resp內容寫入data.txt
3、下載圖片到本地
#coding:utf-8 import urllib pic=urllib.urlopen('http://www.xdowns.com/image/logo.png').read() with open('1.jpg','wb') as fw: #以二進制格式寫圖片文件 fw.write(pic)