首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PYTHON头实验室第3章Msg到Twitter

PYTHON头实验室第3章Msg到Twitter
EN

Stack Overflow用户
提问于 2014-08-19 11:58:29
回答 1查看 309关注 0票数 0
代码语言:javascript
复制
import urllib.request 
import time 

def send_to_twitter(msg):
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API", "http://twitter.com/statuses", "*****", "*****")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode( {'status': msg} )
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
    resp.read()

def get_price():
    page = urllib.request.urlopen("file:///C:/Users/Troll/Documents/lol/Chap%202/offlineV.html")
    text = page.read().decode("utf8")
#finder og assigner index for '>$'
    where = text.find('>$')
#sop-start of price // eop-end of price
    sop = where + 2
    eop = sop + 4
    return float(text[sop:eop])

price_now = input("Do you want to see the price now (Y/N)?")

if price_now == "Y":
    send_to_twitter(get_price())
else:
    price = 99.99
    while price > 4.74:
        time.sleep(15)
        price = get_price()
    send_to_twitter("Buy!")

错误

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\Troll\Documents\lol\Chap 3\chap3.py", line 27, in <module>
    send_to_twitter(get_price())
  File "C:\Users\Troll\Documents\lol\Chap 3\chap3.py", line 11, in send_to_twitter
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
  File "C:\Python34\lib\urllib\request.py", line 153, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python34\lib\urllib\request.py", line 453, in open
    req = meth(req)
  File "C:\Python34\lib\urllib\request.py", line 1120, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
EN

回答 1

Stack Overflow用户

发布于 2014-08-19 13:15:58

你需要:

  • 在发送到urlencode()之前,将urlopen()的输出转换为字节。
  • 相应地解码响应

所以代码看起来是:

代码语言:javascript
复制
def send_to_twitter(msg):
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API", "http://twitter.com/statuses", "*****", "*****")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)

    params = urllib.parse.urlencode( {'status': msg} )
    params = params.encode('utf-8') # Encode with utf-8

    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
    resp.read().decode('utf-8') # Decode using utf-8

检查如何正确使用urllib进行POST

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25382839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档