从我的Twitter脚本返回TypeError

时间:2014-05-03 09:27:01

标签: python twitter typeerror

我是Python的新手(以及一般的编程),所以我一直在寻找我的问题的明显答案,但到目前为止还没有出现......

我正在通过Head First Programming工作,它指示我使用一个它没有解释过的脚本 - 所以如果它不是&#39,几乎没有指导如何修复它工作。

脚本如下:

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", "username", "password")
    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("http://beans.itcarlow.ie/prices.html")
    text = page.read().decode("utf8")
    where = text.find('>$')
    start_of_price = where + 2
    end_of_price = start_of_price + 4
    return float(text[start_of_price:end_of_price])

price_now = input("Do you want to see the price now?(Y/N)")
if price_now == "Y":
    send_to_twitter(get_price())
    price = 99.99
    while price > 4.74:
        time.sleep(900)
        price = get_price()
    send_to_twitter(get_price())

脚本的目的是从网站上提取价格并将其发布到Twitter。然而,将价格发布到Twitter的部分似乎存在一些问题,因为它返回了这个错误:

Traceback (most recent call last):
  File "C:/Users/e53554/Desktop/Misc/Python/Portable Python 3.2.5.1/coffee", line 25, in <module>
    send_to_twitter(get_price())
  File "C:/Users/e53554/Desktop/Misc/Python/Portable Python 3.2.5.1/coffee", line 12, in send_to_twitter
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
  File "C:\Users\e53554\Desktop\Misc\Python\Portable Python 3.2.5.1\App\lib\urllib\request.py", line 139, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\e53554\Desktop\Misc\Python\Portable Python 3.2.5.1\App\lib\urllib\request.py", line 368, in open
    req = meth(req)
  File "C:\Users\e53554\Desktop\Misc\Python\Portable Python 3.2.5.1\App\lib\urllib\request.py", line 1071, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

因此,如果有人可以提供一些关于出错的指导以及我如何解决它,我将永远感激不尽!

亲切的问候

强尼

1 个答案:

答案 0 :(得分:0)

send_to_twitter(bytes(get_price()))