【Python】urlopen小結


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)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM