有道网络查词的简单分析

这是个很简单的任务。友情提示:只能用作学习目的,严禁一切其他用途。

首先,wireshark一类的软件,在查词的时候抓个包,很容易就把 URL 取到了。

然后,这个URL可以简化一下:
http://dict.youdao.com/search?keyfrom=deskdict.main&q=hello&xmlDetail=true&doctype=xml&xmlVersion=8.1
其中q=这个参数就是要查的词了。

返回的结果是一个XML,这个XML也很容易看懂,作为练习,只把简单的释义取出来了。Python 3.3.2。

#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

# YoudaoDictSearch.py

import sys
import urllib.request
import xml.etree.ElementTree

queryurl = 'http://dict.youdao.com/search?keyfrom=deskdict.main&q={0}&xmlDetail=true&doctype=xml&xmlVersion=8.1'

def query(word):
    # 获取查询内容,XML 格式
    resp = urllib.request.urlopen(queryurl.format(word))
    con = resp.read()
    
    # 保存文件
    with open(word+'.xml', 'wb') as f:
        f.write(con)
    
    # 解析 XML 
    tree = xml.etree.ElementTree.fromstring(con)
    
    # 只获取简单的基础释义
    word = tree.find('basic/simple-dict/word')
    
    # word 下有这个主要的子节点: 
    # return-phrase 应该是纠正过拼写错误的单词
    # speech 发音的单词, 可能有 ukspeech 和 usspeech 等
    # phone 单词的音标, 可能有 ukphone 和 usphone 等
    # trs 是释义 (translation?)
    # wfs 分词, 包括现在分词, 过去式, 过去分词, 单复数等
    
    # 可以直接用 word[0], word[1], word[2] 依次表示这些子节点
    # 但为了顺序无关,所以还是查询一下
    
    # phrase
    phrase   = word.find('return-phrase')
    # speech
    speech   = word.find('speech')
    ukspeech = word.find('ukspeech')
    usspeech = word.find('usspeech')
    # phone
    phone    = word.find('phone')
    ukphone  = word.find('ukphone')
    usphone  = word.find('usphone')
    # trs
    trs      = word.find('trs')
    
    # phrase 和 trs 是一样的格式,节点的内容都是:
    # <l><i>TEXT</i></l>
    # 但 trs 可能有多个子节点
    # speech 和 phone 可以直接取节点文本
    phrase_text = phrase[0][0].text
    phone_text  = ''
    if phone is not None:
        phone_text += '[' + phone.text + ']'
    if usphone is not None:
        phone_text += '美[' + usphone.text + ']'
    if ukphone is not None:
        phone_text += '英[' + ukphone.text + ']'
    #trs_text    = trs[0][0].text
    trs_text    = ''
    for sub in trs:
        trs_text += sub[0][0].text + '\n'
    #speech_text = speech.text
    
    # 把音标、释义打印出来就可以了
    print('{0}:\n{1}\n{2}'.format(phrase_text, phone_text, trs_text))

然后就是看运行结果了。

会有一些问题,比如URL的quote啊,各种异常啊等等。

原文地址:https://www.cnblogs.com/zhangbaoqiang/p/3098571.html