idf实验室--简单编程字符统计
生活随笔
收集整理的這篇文章主要介紹了
idf实验室--简单编程字符统计
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
idf實驗室--簡單編程字符統計,有需要的朋友可以參考下。
第一眼看這道題很簡單,不就是字符統計么,可是題目要求2s內回答,而且每次打開的頁面需要統計的字符串內容都會變,這就蛋疼了,于是乎上網學習下如何提交post表單,然后用python寫個程序自動提交就ok了 ( 題目地址 )?
代碼如下:
# -*- coding: utf-8 -*- import urllib2 import urllib import cookielib import string import re#需要提交post的url TARGET_URL = "http://ctf.idf.cn/game/pro/37/"# 設置一個cookie處理器 req = urllib2.Request(TARGET_URL) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) res = opener.open(req)# 通過正則匹配抓到需要統計的字符串 content = res.read() check_text = re.findall(r'<hr />(.*)<hr />',content,re.S)[0]# 簡單的統計 char_count = [0,0,0,0,0] for txt in check_text:if txt == 'w':char_count[0] += 1elif txt == 'o':char_count[1] += 1elif txt == 'l':char_count[2] += 1elif txt == 'd':char_count[3] += 1elif txt == 'y':char_count[4] += 1#將數字轉換成字符串 result = "" for nIndex in char_count:result += str(nIndex) print "Result = ", result# 接下來就是提交了 value = {'anwser': result} data = urllib.urlencode(value) request = urllib2.Request(TARGET_URL,data) response = opener.open(request) html = response.read() print html
需要注意的地方:你需要保存下來第一次正則匹配時打開頁面cookie,構造一個opener,在第二次提交時使用之前的cookie即可。。。否則會提示超時
下面是一個大牛給我的代碼,用到了第三方庫mechanize:
# coding=utf-8import re import urllib2 import mechanizeTARGET_URL = "http://ctf.idf.cn/game/pro/37/" USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36 QQBrowser/3.5.3420.400"# Get target text use regular expression. def get_text(content):return re.findall(r'<hr />(.*)<hr />', content,re.S)[0]def submit():char_count = [0, 0, 0, 0, 0]br_controller = mechanize.Browser()br_controller.set_handle_equiv(True)br_controller.set_handle_redirect(True)br_controller.set_handle_referer(True)br_controller.set_handle_robots(False)br_controller.addheaders = [("User-Agent", USER_AGENT)]br_controller.open(TARGET_URL)# Get web page cotentpage_content = br_controller.response().read()# Get target textcheck_text = get_text(page_content)# Calculatefor txt in check_text:if txt == 'w':char_count[0] += 1elif txt == 'o':char_count[1] += 1elif txt == 'l':char_count[2] += 1elif txt == 'd':char_count[3] += 1elif txt == 'y':char_count[4] += 1# Change value in char_count to string.result = ""for nIndex in char_count:result += str(nIndex)print "Result = ", result# Post form.br_controller.select_form(nr=0)br_controller.form['anwser'] = resultbr_controller.submit()print br_controller.response().read()if __name__ == '__main__':submit()
總結
以上是生活随笔為你收集整理的idf实验室--简单编程字符统计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抓到一只苍蝇 writeup
- 下一篇: brainfu*k语言执行