使用python抓取有道詞典的網頁並返回結果資訊

來源:互聯網
上載者:User

使用Python寫了一個抓取有道詞典首頁的指令碼,目前功能還不完善,只能抓取基本的Tag並使用BeautifulSoup顯示出來,沒有對Tag裡的資訊進行細分。另外,網頁端是按utf-8編碼的,放到Windows上的命令列裡無法正常顯示,目前還沒有測試Linux終端裡的情況。有時間再完善一下吧。

#! /usr/bin/python# coding = utf-8# youdao.py# To-do: get meaning of a word from youdao.com# Author: Steven# Date: 2013/04/21import urllib, urllib2from bs4 import BeautifulSoupimport sysinputDecode = sys.stdin.encodingoutputDecode = sys.stdout.encodingdef getHtml(word = 'bless'):#word = raw_input("Please input your word:")youdaoHtml = 'http://dict.youdao.com/search'youdaoData = {'le': 'eng', 'q': word, 'keyfrom': 'dict'}youdaoRequest = urllib2.Request(youdaoHtml, urllib.urlencode(youdaoData))youdaoRequest.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)')wordHtml = urllib2.urlopen(youdaoRequest)return wordHtml.read().decode('utf-8')def showMeaning(word = 'bless'):word = raw_input('Please input your word:')wordSoup = BeautifulSoup(getHtml(word))# show the wordprint "Word:\t", wordSoup.find('span', {'class', 'keyword'}).string# show the pronounceprint "Prounaounciation:\t",for prons in wordSoup.find_all('span', {'class', 'phonetic'}):print prons.string.encode('utf-8'),# show meaningprint 'Meaning:\n'for meaning in wordSoup.find_all('span', {'class', 'def'}):print '***\t', meaning.string.encode(outputDecode)def sample(word = 'bless'):while 1:print "Input C to continue, input Q/q to quit.\n"selection = raw_input("Please input your command\n>>>")if selection in ['C', 'c']:showMeaning(word)elif selection in ['Q', 'q', 'quit', 'Quit']:breakelse:exit()if __name__ == '__main__':sample()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.