Python實踐之網絡編程1-簡單的網絡請求程序


在了解python基礎的語法基礎上,就可以自由的去組合出自己需要各類高級功能。

由於python語言的特性,各類功能的實現都會非常快捷的。
網絡變成就是python具備的高級特性之一。
 
需要進行網絡編程首先需要了解幾個模塊urllib和urllib2
 
 
1.簡單的訪問請求
import sys,urllib,urllib2

url=input("please input the url:")
url = "http://mail.126.com"

#發起請求
req = urllib2.Request(url)
fd = urllib2.urlopen(req)


#輸出結果
#print fd.read()
print ("URL Retrieved:",fd.geturl())
info = fd.info()
for key, value in info.items():
    print "%s           =              %s" % (key,value)

while True:
    data = fd.read(1024)
    if not len(data):
            break
    #print data
    
    

 

2.簡單的get請求
#構造get參數
#zipcode = sys.argv[1]
wd = input("search word:")
data = urllib.urlencode([('wd',wd)])

#構造url 拼接請求參數
url= "http://www.baidu.com"
url = url + "?" + data
print 'ursing url', url

#構造request 並請求
req = urllib2.Request(url)
fd = urllib2.urlopen(req)

#讀取相應結果
while True:
    data = fd.read(1024)
    if not len(data):
        break
    #sys.stdout.write(data)
    print data

 

3.簡單的post請求
和get請求最大的差別其實就是將請求參數放到了請求體中,而不是拼接到url中
import sys,urllib,urllib2


#構造參數
#zipcode = sys.argv[1]
wd = input("search word:")
data = urllib.urlencode([('wd',wd)])

#構造url 不需要將參數拼接到url中
url= "http://www.baidu.com"
print 'ursing url', url

#構造request 只需要將參數放到urlopen的第二個參數里
req = urllib2.Request(url)
fd = urllib2.urlopen(req,data)

#讀取相應結果
while True:
    data = fd.read(1024)
    if not len(data):
        break
    #sys.stdout.write(data)
    print data

 

 
 
 
4.登陸驗證功能
等登陸驗證有很多種方式,最常見的是post表單或者cookie形式的登陸驗證。此類形式的的驗證和post請求可能關系更加密切。
這里是最基本的http驗證,由客戶端向服務器端發送用戶名密碼。形式上一般會彈出一個登陸窗口
 
import sys,urllib,urllib2,getpass

#定義TerminalPwd類擴展HTTPPasswordMgr,允許在需要的時候詢問操作員輸入密碼
class TerminalPwd(urllib2.HTTPPasswordMgr):
    def find_user_password(self,realm,authuri):
        retval = urllib2.HTTPPasswordMgr.find_user_password(self,realm,authuri)
        
        if retval[0] == None and retval[1] == None:
            #didn't find it in stored values
            username = input("Login required,please input username:")
            password = input("please input password:")
            return(username,password)
        else:
            return retval


url = "http://home.asiainfo.com/"
req = urllib2.Request(url)
#需要加載額外的處理時需要使用opener,比如此處需要支持認證處理
#如果需要認證,會自動調用TerminalPwd里面的函數,如果不需要進一步檢查和普通的請求一樣
opener =  urllib2.build_opener(urllib2.HTTPBasicAuthHandler(TerminalPwd()))

#請求
fd = opener.open(req)

print ("URL Retrieved:",fd.geturl())
info = fd.info()
for key, value in info.items():
    print "%s           =              %s" % (key,value)
    

 

 
 
 
 
 


免責聲明!

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



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