我有一个使用python 3和FancyURLopener通过https登录的脚本。 所以我这样做:
from urllib.request import FancyURLopener, urlopen
from urllib.parse import urlencode
import re, sys
class SMS:
login_url = "url1"
login_act = "url2"
comp_url = "url3"
comp_act = "url4"
LEN = 100
def __init__(self, phone_num, password):
self.phone_num = phone_num
self.password = password
self.opener = FancyURLopener()
resp = self.opener.open(SMS.login_url)
cookie = ""
for x, y in resp.headers.items():
if x == "Set-Cookie":
cookie += y + "; "
cookie = cookie[:-2]
self.opener.addheader("Cookie", cookie)
print("--login")
self.login()
def login(self):
di = { "action":"", "refid":"", "continuation":"",\
"username":self.phone_num, "password":self.password, "image.x":"45", "image.y":"18"}
resp = self.opener.open(SMS.login_act, urlencode(di))
def send(self, to, message):
print("--sending")
if len(message) > 100:
print("Message length too long; Not send.")
return -1
resp = self.opener.open(SMS.comp_url).read().decode("windows-1251")
pattern1 = "<input type=\"hidden\" name=\"daycreditsmsleft\" value=\"(\d+)\""
pattern2 = "<input type=\"HIDDEN\" name=\"smssenttime\" value=\"(\d+)\""
post = {"brand":"", "daycreditsmsleft":re.search(pattern1, resp).groups()[0],\
"process":"true", "btnSendSMS.x":"75", "btnSendSMS.y":"23", "model":"0",\
"smssenttime":re.search(pattern2, resp).groups()[0], "remainingChars": str(SMS.LEN - len(message)),\
"reply2inbox":"false", "selReceiverName":"", "txtareaMessage":message, "receiverPhoneNum":to}
if post["daycreditsmsleft"] == 0:
print("No more messages; Not send")
return -1
resp = self.opener.open(SMS.comp_act, urlencode(post) )
然后我将这样使用它:
s = SMS("telephone_num", "pass")
s.send(tel, message)
问题是POST请求太慢。登录需要20多秒。 在整个脚本中有2个POST请求,因此它实际上在一分钟内运行。如何优化它?
我还注意到在程序结束之前收到了消息。
答案 0 :(得分:1)
我的猜测是,请求中存在一些微妙的不同,这会使您的服务器在处理请求时花费很长时间。
如果您是服务器的编写者,这应该很容易验证。如果不是,您可能必须使用某种跟踪程序,这样您就可以看到从Python端完成请求的时间,并查看响应何时返回,并将其与浏览器的请求进行比较。