这是一个小小的程序,为了练习requests,爬取墨迹天气
import requests
from lxml.html import etree
import json
import time # 导入模块
class MoJiWeather():
def city_name(self): # 定义一个输入城市名称的函数
cityname = str(input("输入城市名称:"))
return cityname
def search_city(city_name): # 搜索这个城市
index_url = "http://tianqi.moji.com/api/citysearch/%s"%city_name # 构造查询相应城市天气的url
response = requests.get(index_url)
response.encoding = "utf-8"
try: # 异常捕获
city_id = json.loads(response.text).get('city_list')[0].get('cityId')# 通过上面的url获取城市的id
city_url = "http://tianqi.moji.com/api/redirect/%s"%str(city_id) # 通过城市id获取城市天气
return city_url
except:
print('城市名输入错误')
exit()
def pa