本文實例講述了Python實現自動登錄百度空間的方法。分享給大家供大家參考,具體如下:
開發環境:Fedora12 + Python2.6.2
#!/usr/bin/python# coding: GBKimport urllib,urllib2,httplib,cookielibdef auto_login_hi(url,name,pwd):  url_hi="http://passport.baidu.com/?login"  #設置cookie  cookie=cookielib.CookieJar()  cj=urllib2.HTTPCookieProcessor(cookie)  #設置登錄參數  postdata=urllib.urlencode({'username':name,'password':pwd})  #生成請求  request=urllib2.Request(url_hi,postdata)  #登錄百度  #opener=urllib2.build_opener(request,cj)  opener=urllib2.build_opener(cj)  f=opener.open(request)  #打開百度HI空間頁面  hi_html=opener.open(url)  return hi_htmlif __name__=='__main__':  name='zhouciming'  password='xxx'  url='http://hi.baidu.com/zhouciming'  h=auto_login_hi(url,name,password)  print h.read()運行結果:
[zcm@python #33]$./bai.py<!DOCTYPE html><HTML XMLNS="http://www.w3.org/1999/xhtml" LANG="zh-CN"><HEAD><!--STATUS OK--> <META http-equiv="Content-Type" CONTENT="text/html;charset=GBK" /> <TITLE>個人主頁</TITLE></HEAD><BODY><script language="javascript">location.href="/zhouciming/home" rel="external nofollow" ;</script></BODY></HTML>
通過運行結果可以看到,登錄成功了。網頁自動跳轉到 /zhouciming/home
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python Socket編程技巧總結》、《Python URL操作技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答