python3下的twistedPOST请求网页

在python2中我们使用twisted比较方便,网上资料也比较多,但是通常在python3中使用的时候,并不能成功。我也是找了好多资料没有成功之后,自己去尝试做小白鼠,测试了很久之后,发现传递给twisted的所有数据都需要是bytes类型的。直接看代码吧(亲测可用):

from twisted.internet import reactor
from twisted.web.client import getPage
import urllib.parse

num = 0

a = []


def one_done(arg):
    global num
    print(type(arg))
    print(arg.decode())
    a.append(arg)
    num += 1
    if num == 3:
        reactor.stop()


cookies = {
    b'123': b'654'
}
post_data = urllib.parse.urlencode({'check_data': 'adf'})
post_data = bytes(post_data, encoding='utf8')
headers = {b'Content-Type': b'application/x-www-form-urlencoded'}
for i in range(3):
    response = getPage(bytes('http://dig.chouti.com/login', encoding='utf8'),
                       method=bytes('POST', encoding='utf8'),
                       postdata=post_data,
                       headers=headers,
                       cookies=cookies)
    response.addBoth(one_done)

reactor.run()

print(a)
要注意的是,postdata这个字典是直接转换为字符串然后转换为bytes,headers和cookies只是将键和值转换为bytes类型了。

 

注意:postdata这个字典是直接转换为字符串然后转换为bytes,headers和cookies只是将键和值转换为bytes类型了。

转载于:https://www.cnblogs.com/sxzwj/p/6846486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值