python模拟浏览器模块,python模块学习---mechanize(模拟浏览器)
mechanize是非常合適的模擬瀏覽器的模塊。
它的特點(diǎn)主要有:
1 http,https協(xié)議等。
2 簡(jiǎn)單的HTML表單填寫。
3 瀏覽器歷史記錄和重載。
4 Referer的HTTP頭的正確添加(可選)。
5 自動(dòng)遵守robots.txt的。
6 自動(dòng)處理HTTP-EQUIV和刷新。
所以你可以用mechanize來完成一些自動(dòng)化瀏覽器想要做的事情,比如自動(dòng)登錄表單,自動(dòng)填寫表單等。
首先你在
mechanize download頁(yè)面
里面下載并且安裝好
然后可以看下文檔:
http://wwwsearch.sourceforge.net/mechanize/
下面是我寫的簡(jiǎn)單代碼:
#導(dǎo)入模塊##
import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)##關(guān)聯(lián)cookies
###設(shè)置一些參數(shù),因?yàn)槭悄M客戶端請(qǐng)求,所以要支持客戶端的一些常用功能,比如gzip,referer等
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
###這個(gè)是degbug##你可以看到他中間的執(zhí)行過程,對(duì)你調(diào)試代碼有幫助
br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.11) Gecko/20100701 Firefox/3.5.11')]##模擬瀏覽器頭
response = br.open('http://xxx..com/')##自己設(shè)定一個(gè)url
for f in br.forms():##有的頁(yè)面有很多表單,你可以通過來查看
print f
br.select_form(nr=1)##選擇表單1,
br.form['username'] = '用戶賬戶'
br.form['password'] = '密碼'
br.submit()##提交表單
print 'success login'
總結(jié)
以上是生活随笔為你收集整理的python模拟浏览器模块,python模块学习---mechanize(模拟浏览器)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php mssql生僻字,php生僻字的
- 下一篇: python flask与django的