首页 > 解决方案 > Head First Programming Python 3:Twitter 错误

问题描述

我正在使用 Python 3

我是初学者,正在努力学习编程。我正在使用 Paul Barry 和 David Griffiths 的《Head First Programming》一书。因此,在第 3 章第 92-98 页的某处,该书指示编写一个程序,以便经理将通过其 Twitter 帐户直接发送产品价格或何时购买

所以这是我使用的代码,这与书中的代码相同:

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-r-us.appspot.com/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())
else:
    price = 99.99
    while price > 4.74:
        time.sleep(900)
        price = get_price()
send_to_twitter("Buy!")

在用户名和密码部分,我使用了自己的 Twitter 帐户,但我当然不能在这里显示。

所以我输入错误后发生的事情是:

Do you want to see the price now (Y/N)? Y

   Traceback (most recent call last):
  File "C:\Users\BEST\Desktop\python\headfirsttrychapter3.5.py", line 24, in <module>
    send_to_twitter(get_price())
  File "C:\Users\BEST\Desktop\python\headfirsttrychapter3.5.py", line 13, in send_to_twitter
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
  File "C:\Users\BEST\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\BEST\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 523, in open
    req = meth(req)
  File "C:\Users\BEST\AppData\Local\Programs\Python\Python37\lib\urllib\request.py", line 1247, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

为什么会这样?我该如何解决这个问题?:( 非常感谢

标签: pythonpython-3.x

解决方案


推荐阅读