【发布时间】:2011-06-06 03:55:03
【问题描述】:
我有一个脚本,它使用 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 请求,因此它实际上运行了将近一分钟。如何优化?
我还注意到消息是在程序结束之前收到的。
【问题讨论】:
-
“太慢了”?您是否尝试过手动登录(使用浏览器)?那是不是更快了?快多少?可以发一下手动和
urllib的时间对比吗? -
如果可能,请提供所有详细信息(例如 cookie、用户名、密码和 url)以重现此内容。问题可能不在于您提供的代码,我怀疑这可能没有得到答复。
-
使用浏览器立即记录。我将添加所有代码。
-
“立即”?你可以尝试测量它吗?请注意,您的代码中涉及两个页面加载,您需要同时测量两者。显示登录表单的页面和登录后的页面。这 - 诚然 - 难以衡量,因为您必须键入并单击(或粘贴并单击,或等待浏览器自动填充字段)。
-
登录时使用 Firebug:1.99 秒(加载 2.35),手动使用 urllib:~21 秒。这仅用于登录。来自浏览器的另一个请求是 2.13,同样是 urllib:~21 秒。奇怪的是,在我的程序打印“--sending”后几乎立即(约 1-2 秒)收到消息,但随后它停止了。
标签: python http post python-3.x urllib