利用python實(shí)現(xiàn)一個(gè)在線查詞軟件色鸳,效果如圖
1.觀察網(wǎng)頁結(jié)構(gòu)杠览,確定方法
待會要用到的有三處:鏈接,headers,和data,gui就采用最簡單的tkinter,網(wǎng)頁請求用requests,解析數(shù)據(jù)用json
url = "https://aidemo.youdao.com/trans"
headers = {
? ? ? ? 'Accept': 'application/json, text/javascript, */*; q=0.01',
? ? ? ? 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
? ? ? ? 'Origin': 'http://ai.youdao.com',
? ? ? ? 'Referer': 'http://ai.youdao.com/product-fanyi.s',
? ? ? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
? ? }
data = {
? ? ? ? 'from': 'Auto',
? ? ? ? 'to': 'Auto'
? ? }
準(zhǔn)備好之后訪問會返回一個(gè)json字符串植锉,可以用python自帶的json進(jìn)行解析
所用代碼如下
#!/usr/bin/python3
from tkinter import *
import requests
import json
root=Tk()
entry1=Entry(root,width=50)
entry1.pack()
value1=StringVar()
value2=StringVar()
def query():
? ? url = "https://aidemo.youdao.com/trans"
? ? headers = {
? ? ? ? 'Accept': 'application/json, text/javascript, */*; q=0.01',
? ? ? ? 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
? ? ? ? 'Origin': 'http://ai.youdao.com',
? ? ? ? 'Referer': 'http://ai.youdao.com/product-fanyi.s',
? ? ? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
? ? }
? ? data = {
? ? ? ? 'from': 'Auto',
? ? ? ? 'to': 'Auto'
? ? }
? ? data['q']=entry1.get()
? ? response = requests.post(url=url, headers=headers, data=data)
? ? cihui = json.loads(response.content)
? ? entry2.select_clear()
? ? entry2.insert(0, cihui['web'][0]['value'])
button = Button(root, text="query", command=query).pack()
entry2 = Entry(root,textvariable=value2,width=50)
entry2.pack()
root.mainloop()
總結(jié)
代碼量不多褪子,關(guān)鍵是分析站的時(shí)間比較多易核,如分析返回的數(shù)據(jù)結(jié)構(gòu)嗅蔬,構(gòu)建索引蜘渣,json一般采用json庫就行济蝉,如果是在網(wǎng)頁中爬取的話杰刽,則可以采用字符串匹配,
和一個(gè)比較新的pyquery庫----->即像jQuery一樣對數(shù)據(jù)進(jìn)行查找王滤。
還有g(shù)ui庫贺嫂,由于本次功能簡單就使用了本身的tkinter,有興趣可以試一下pyqt,wxpython,不過我沒用過
其實(shí)可以用一個(gè)庫把代碼 打包成exe程序,不過建議最好別這樣做雁乡,因?yàn)樯傻奈募艽蟮谠热邕@個(gè)程序差不多十幾兆左右,原理是將pytohn解釋器和所用到的庫全都打包到一起踱稍。
屌絲版查詞軟件就好了曲饱,忽略外觀ok