这是网页:https://www.huobi.com/p/api/contents/
我正在尝试创建一个python代码,告诉我标题是否有任何更改。我正在使用此代码,我收到此错误
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\folder\python.py", line 24, in <module>
before_set = set(before['title'])
KeyError: 'title'
这是我尝试使用的代码
import requests
import json
import smtplib
import time
def build_pair_string(pairs):
pair_string = ""
for pair in pairs:
pair_string += pair + "\n"
return pair_string
try:
with open('marketstrex.json', 'r') as current_markets:
before = json.loads(current_markets.read())
except IOError:
before = requests.get('https://www.huobi.com/p/api/contents/').json()
with open('marketstrex.json', 'w') as current_markets:
current_markets.write(json.dumps(before))
print("First run... Getting initial market data.")
after = requests.get('https://www.huobi.com/p/api/contents/').json()
before_set = set(before['title'])
after_set = set(after['title'])
new_set = after_set - before_set
if not new_set:
print("No change... Exiting.")
time.sleep(5)
if new_set:
with open('marketstrex.json', 'w') as current_markets:
current_markets.write(json.dumps(after))
print('Huobi changes:')
new_list = []
for pair in new_set:
new_list.append(pair) # = [item for item in pair]
print(new_list)
sender = 'example@example.com'
receivers = ['example@example.com']
message = """
Huobi changes:\n{}\n
""".format(build_pair_string(new_list))
try:
smtpObj = smtplib.SMTP_SSL('smtp.gmail.com:465')
smtpObj.login('example@example.com','password')
smtpObj.sendmail(sender, receivers, message)
print("\nSuccessfully sent email")
except SMTPException:
print("\nError: unable to send email")
它可以告诉我网页是否有任何变化,但显然,它没有做任何事情/无法判断是否有变化
请指教!
答案 0 :(得分:0)
获取数据表明顶级JSON结构中没有title
。有一个data
元素是一个包含title
元素的字典。也许这就是你要提取的内容?
data
元素还包含一个成员top_notice_list
,该成员是一个元素列表,每个元素都有一个title
元素。