求大神分析一下我的python脚本慢在哪里?
请大神们分析下这个python脚本为什么会运行这么慢.
初衷 : 公司有个料号系统, 在网站上输入料号就能查询相关的资料, 一般情况下, 我会ctrl+c, 打开网站, ctrl+v, 点击查询, 得到资料.
脚本实现方式 : 我ctrl+c料号, 脚本调用windows的clipboard API, 拿到所复制的text, 然后用requests模拟正常浏览器的GET, 最后通过webbrowser模块打开得到的HTML.
问题 : 速度很慢, 可以说比我手动在浏览器上看要慢. 基本超过6s..有什么办法可以改良呢?
谢谢!
"""
work flow: get text content like "23.34239.394"( PN format) from
clipboard, making a GET request using requests, with URL parameter
PartNumber=text, and then open its html text with webbrowser module.
"""
import ctypes
import requests
import os
import webbrowser
def spec():
# clipboard format TEXT defined by MS
CF_TEXT = 1
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32
user32.OpenClipboard(0)
if user32.IsClipboardFormatAvailable(CF_TEXT):
data = user32.GetClipboardData(CF_TEXT)
data_locked = kernel32.GlobalLock(data)
text = ctypes.c_char_p(data_locked)
print(text.value)
kernel32.GlobalUnlock(data_locked)
else:
print('no text in clipboard')
user32.CloseClipboard()
# decode bytes to unicode string
s = text.value.decode()
# fork a browser GET request
url = 'http://wpqssvr.wistron.com.tw:7001/wpqs/servlet/COM.qpart.Attachment'
para = {'PartNumber': s}
h = {
'Accept': 'text/html',
'Connection': 'keep-alive',
'Host': 'wpqssvr.wistron.com.tw:7001',
'Accept-Language': 'zh-TW',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0;rv:11.0) like Gecko'
}
# make the request and stores the html into temp file, open with IE
try:
r = requests.get(url, params = para, headers=h)
path = os.path.abspath('temp.html')
url = 'file://' + path
with open(path, 'w') as f:
f.write(r.text)
webbrowser.open_new_tab(url)
except:
print('open url or open file fails')
raise
exit()
if __name__ == '__main__':
spec()
无良MOA
10 years ago