import urllib.request
def get_price():
page=urllib.request.urlopen("http://www.baidu.com")
text=page.read().decode("utf8")
where=text.find('="')
start_of_price=where+2
end_of_price=start_of_price+4
print(text[start_of_price:end_of_price])
get_price()
加入函數的取價格程式:
import urllib.request
import time
def get_price():
page=urllib.request.urlopen("http://www.beans-r-us.biz/price.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("現在需要價格嗎(Y/N)?")
if price_now=="Y":
print(get_price())
else:
price=99.99
while peice>4.47:
time.sleep(900)
price=get_price()
print("Buy!")
向Twitter發送消息! send_to_twitter()函數?
import urllib.request
import time
def get_price():
page=urllib.request.urlopen("http://www.beans-r-us.biz/price.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])
def send_to_twitter():
msg="I am a message that will be sent to Twitter"
password_manager=ullib.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.reques.install_opener(page_opener)
params=urllib.parse.urlencode
({'status':msg})
resp=urllib.request.urlop
("http://twitter.com/statueses/update.json",params)
resp.read()
price_now=input("現在需要價格嗎(Y/N)?")
if price_now=="Y":
send_to_twitter()
else:
price=99.99
while peice>4.47:
time.sleep(900)
price=get_price()
send_to_twitter()
修改為可以傳參的函數
import urllib.request
import time
def get_price():
page=urllib.request.urlopen("http://www.beans-r-us.biz/price.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])
def send_to_twitter( msg):
password_manager=ullib.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.reques.install_opener(page_opener)
params=urllib.parse.urlencode
({'status':msg})
resp=urllib.request.urlop
("http://twitter.com/statueses/update.json",params)
resp.read()
price_now=input("現在需要價格嗎(Y/N)?")
if price_now=="Y":
send_to_twitter(get_price())
else:
price=99.99
while peice>4.47:
time.sleep(900)
price=get_price()
send_to_twitter("Buy!")
總結:
由于自己沒有Twitter賬戶自己無法驗證程式的正誤。也想注冊一個Twitter賬戶試一下。但是始終無法進入Twitter官網!