Python提取网页中内容写入Json并打包成exe文件

作者 Zhs 日期 2016-06-18
Python提取网页中内容写入Json并打包成exe文件

背景介绍:
影梭提供三个免费的账号可供使用,但六小时更换一次密码,每次打开网页粘贴密码的过程机器繁琐。遂想到利用python自动完成这一过程。

提取网页中密码

这里用了很基础的方法

#直接爬到首页的全部内容
request = urllib2.Request("http://www.ishadowsocks.net/")
response = urllib2.urlopen(request)
#定义提取的函数
#匹配模式,待匹配字符串,序号(第几个匹配到的)
def extractData(regex, content, index):
r = '0'
p = re.compile(regex)
m = p.search(content)
if m:
r = m.group(index)
return r
#定义匹配模式'()'内为要提取的内容(这里是谷歌来的, `.*`代表全部内容 )
#[r'A密码:(.*)</h4>'],将匹配的字符串转换为对象
regexA = r'A密码:(.*)</h4>'
regexB = r'B密码:(.*)</h4>'
regexC = r'C密码:(.*)</h4>'
content = response.read()
index = 1
keyA=extractData(regexA, content, index)
keyB=extractData(regexB, content, index)
keyC=extractData(regexC, content, index)
写入配置文件
#json格式读取配置文件
f2 = file('gui-config.json')
s = json.load(f2)
f2.close()
#更改对应密码
s['configs'][0]['password'] = keyA
s['configs'][1]['password'] = keyB
s['configs'][2]['password'] = keyC
#写入密码
with open('gui-config.json', 'w') as f:
json.dump(s, f)
f.close()
编译成可执行文件
  • 安装pip工具

    python get-pip.py
  • 安装pyinstaller

    pip install pyinstaller
  • 打包

    pyinstaller myscript.py

    | -D, –onedir | Create a one-folder bundle containing an executable (default) |
    | ————- | —————————————- |
    | -F, –onefile | Create a one-file bundled executable. |
    | –specpathDIR | Folder to store the generated spec file (default: current directory) |

完整代码
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 18 09:07:19 2016

@author: Zhs
"""

import json
import urllib2
import re

request = urllib2.Request("http://www.ishadowsocks.net/")
response = urllib2.urlopen(request)

#print response.read()

def extractData(regex, content, index):
r = '0'
p = re.compile(regex)
m = p.search(content)
if m:
r = m.group(index)
return r
#regex = r'密码:(.*)</h4>'
regexA = r'A密码:(.*)</h4>'
regexB = r'B密码:(.*)</h4>'
regexC = r'C密码:(.*)</h4>'
content = response.read()
index = 1
keyA=extractData(regexA, content, index)
keyB=extractData(regexB, content, index)
keyC=extractData(regexC, content, index)
s = 'US:'+keyA+'\nHK:'+keyB+'\nJP:'+keyC
print s
# Reading data back
#with open('data.json', 'r') as f2:
#data = json.load(f2)
#json.dump(data, f)
f2 = file('gui-config.json')
s = json.load(f2)
f2.close()
s['configs'][0]['password'] = keyA
s['configs'][1]['password'] = keyB
s['configs'][2]['password'] = keyC
#json.dumps(s, sort_keys=True, indent=2)
with open('gui-config.json', 'w') as f:
json.dump(s, f)
f.close()