Python learning notes: "crawler + youdao Dictionary" implements a simple ing program, python learning notes
1. youdao Translation
Webpage: www.youdao.com
Figure 1
Figure 2
Figure 3
Figure 4
Click "automatic translation" again-> select 'network'-> select 'first Project', as shown below:
Figure 5
Then, the following content is displayed. The red box shows the content that will be needed to write the code:
Figure 6
Figure 7
Let's look at the Translation results:
Fig8
2. python implementation:
Principle: input the content to be translated to the youdao dictionary, and then crawl the translation result through the program.
1 #-*-coding: UTF-8-*-2 "3 Created on Sun May 03 09:36:12 2015 4 5 @ author: 90 Zeng 6 "7 8 import urllib 9 import json10 11 # note that unicode encoding is used here; otherwise, garbled 12 content = input (u" Enter the content to translate: ") 13 # The url is the Response URL14 url = 'HTTP: // fanyi.youdao.com/translate? Smartresult = dict & smartresult = rule & smartresult = ugc & sessionFrom = http://www.youdao.com/'15 # The crawled data format is Form Data16 data = {} 17 data ['type'] = 'in Fig7' AUTO '18 data ['I'] = content19 data ['doctype'] = 'json' 20 data ['xmlversion'] = '1. 6 '21 data ['keyfrom'] = 'fanyi. web '22 data ['ue'] = 'utf-8' 23 data ['typoresresult'] = 'true' 24 25 # data encoding 26 data = urllib. urlencode (data) 27 28 # crawl content from url according to data format 29 response = urllib. urlopen (url, data) 30 # Read the crawled content to the variable string html, 31 html = response. read () 32 # convert the string to the dictionary format shown in Fig8. 33 target = json. loads (html) 34 # according to the format in Fig8, obtain the final translation result 35 result = target ["translateResult"] [0] [0] ['tgt '] 36 37 # Here unicode is used to display Chinese characters, avoid garbled 38 print (u "translation result: % s" % (target ["translateResult"] [0] [0] ['tgt '])
Run:
Learning Materials Source: Little Turtle's video 'getting started with python with zero base'