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 = ""%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 = ""%str(city_id) # 通過城市id獲取城市天氣
return city_url
except:
print('城市名輸入錯誤')
exit()
def parse(city_url): # 解析函式
response = requests.get(city_url)
response.encoding = 'utf-8'
html = etree.html(response.text)
current_city = html.xpath("//div[@class='search_default']/em/text()")[0]# 下面都是利用xpath解析的
print('當前城市:'+current_city)
current_kongqi = html.xpath("//div[@class='left']/div[@class='wea_alert clearfix']/ul/li/a/em/text()")[0]
print('空氣質素:'+current_kongqi)
current_wendu = html.xpath("//div[@class='left']/div[@class='wea_weather clearfix']/em/text()")[0]
print('當前溫度:'+current_wendu+'℃')
current_weather = html.xpath("//div[@class='wea_weather clearfix']/b/text()")[0]
print('天氣狀況:' + current_weather)
current_shidu = html.xpath("//div[@class='left']/div[@class='wea_about clearfix']/span/text()")[0]
print('當前濕度:'+current_shidu)
current_fengji = html.xpath("//div[@class='left']/div[@class='wea_about clearfix']/em/text()")[0]
print('當前風速:'+current_fengji)
jingdian = html.xpath("//div[@class='right']/div[@class='near'][2]/div[@class='item clearfix']/ul/li/a/text()")
print('附近景點:')
for j in jingdian:
print('\t\t'+j)
if __name__ == '__main__':
print("歡迎使用墨跡天氣查詢系統")
city_name = mojiweather.city_name(1)
city_url = mojiweather.search_city(city_name)
mojiweather.parse(city_url)
print("謝謝使用本查詢系統")
input("按任意鍵退出...")
python之利用epoll實現http伺服器
usr bin python3.5 coding utf 8 time 18 7 2 下午7 39 author fengwr email fengwenrui1217 163.com file epoll實現http.py 建立epoll物件 epl select.epoll 將tcp sever...
Python資料分析之利用pandas查詢資料
這裡的查詢資料相當於r語言裡的subset功能,可以通過布林索引有針對的選取原資料的子集 指定行 指定列等。我們先導入乙個student資料集 student pd.io.parsers.read csv c users admin desktop student.csv 查詢資料的前5行或末尾5行...
python學習筆記之利用jieba庫進行詞頻分析
jieba github倉庫位址 詞頻統計 import jieba 沒有安裝jieba庫可以在 使用命令列 pip install jieba 進行自動安裝 deffrequency 讀取檔案 txt open 檔案所在目錄.txt r encoding utf 8 read 這裡檔案路徑位置填寫...