PYTHON headfirstlab Chap 3消息发送给Twi

2024-09-30 05:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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!")

错误

^{pr2}$

Tags: totextsendhttpgetrequestpagemanager
1条回答
网友
1楼 · 发布于 2024-09-30 05:26:59

您需要:

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

所以代码看起来像:

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

Check如何正确使用urllib正确执行POST

相关问题 更多 >

    热门问题