python慢在哪里_求大神分析一下我的python脚本慢在哪里?

博主分享一个Python脚本,该脚本通过调用Windows剪贴板API获取料号,用requests模拟GET请求,再用webbrowser模块打开HTML。但脚本运行速度很慢,超过6秒,比手动操作还慢,博主希望得到改良办法。

请大神们分析下这个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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值