国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

在Python中使用mechanize模塊模擬瀏覽器功能

2020-02-23 01:06:11
字體:
來源:轉載
供稿:網友

知道如何快速在命令行或者python腳本中實例化一個瀏覽器通常是非常有用的。
每次我需要做任何關于web的自動任務時,我都使用這段python代碼去模擬一個瀏覽器。
 

import mechanizeimport cookielib# Browserbr = mechanize.Browser()# Cookie Jarcj = cookielib.LWPCookieJar()br.set_cookiejar(cj)# Browser optionsbr.set_handle_equiv(True)br.set_handle_gzip(True)br.set_handle_redirect(True)br.set_handle_referer(True)br.set_handle_robots(False)# Follows refresh 0 but not hangs on refresh > 0br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)# Want debugging messages?#br.set_debug_http(True)#br.set_debug_redirects(True)#br.set_debug_responses(True)# User-Agent (this is cheating, ok?)br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

現在你得到了一個瀏覽器的示例,br對象。使用這個對象,便可以打開一個頁面,使用類似如下的代碼:
 

# Open some site, let's pick a random one, the first that pops in mind:r = br.open('http://google.com')html = r.read()# Show the sourceprint html# orprint br.response().read()# Show the html titleprint br.title()# Show the response headersprint r.info()# orprint br.response().info()# Show the available formsfor f in br.forms():  print f# Select the first (index zero) formbr.select_form(nr=0)# Let's searchbr.form['q']='weekend codes'br.submit()print br.response().read()# Looking at some results in link formatfor l in br.links(url_regex='stockrt'):  print l

如果你訪問的網站需要驗證(http basic auth),那么:
 

# If the protected site didn't receive the authentication data you would# end up with a 410 error in your facebr.add_password('http://safe-site.domain', 'username', 'password')br.open('http://safe-site.domain')

由于之前使用了Cookie Jar,你不需要管理網站的登錄session。也就是不需要管理需要POST一個用戶名和密碼的情況。
通常這種情況,網站會請求你的瀏覽器去存儲一個session cookie除非你重復登陸,
而導致你的cookie中含有這個字段。所有這些事情,存儲和重發這個session cookie已經被Cookie Jar搞定了,爽吧。
同時,你可以管理你的瀏覽器歷史:
 

# Testing presence of link (if the link is not found you would have to# handle a LinkNotFoundError exception)br.find_link(text='Weekend codes')# Actually clicking the linkreq = br.click_link(text='Weekend codes')br.open(req)print br.response().read()print br.geturl()# Backbr.back()print br.response().read()print br.geturl()

下載一個文件:
 

# Downloadf = br.retrieve('http://www.google.com.br/intl/pt-BR_br/images/logo.gif')[0]print ffh = open(f)            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 耒阳市| 龙陵县| 保德县| 新干县| 沧源| 永寿县| 郸城县| 青浦区| 封开县| 德安县| 枝江市| 黔西县| 亚东县| 鞍山市| 嫩江县| 白山市| 肃宁县| 长宁区| 苏尼特右旗| 益阳市| 吉首市| 新疆| 巨野县| 剑河县| 福州市| 皋兰县| 和林格尔县| 宜阳县| 五家渠市| 青浦区| 女性| 昭苏县| 宜良县| 云龙县| 绥江县| 鹤峰县| 金坛市| 锦屏县| 双柏县| 锦屏县| 临泽县|