python实现一个字典

#!/usr/bin/python
#-*-coding:utf-8-*-

from    selenium    import webdriver
from    bs4         import  BeautifulSoup
#上面两个都是第三方库,请自行下载,还有PhantomJS也要去官网下载安装
def     main():
        while True:
            word = raw_input("输入要查询的单词:")
            driver = webdriver.PhantomJS(r'C:\phantomjs-2.1.1-windows\bin\phantomjs.exe')
            url = "https://www.baidu.com/s?wd=%s"%word
            driver.get(url)#下载网页并且渲染Javascript
            soup = BeautifulSoup(driver.page_source,"html.parser")
            #用Beautiful解析网页
            detail = soup.select("table.op_dict3_english_result_table tbody tr td span")
            sentence = soup.select("div.op_dict3_lineone_result.c-clearfix span")
            chinese = soup.find('div',attrs={"class":"op_dict3_linetwo_result"})
            if len(detail)==0 or sentence==0:
                print "解析错误,请确定输入的是英语单词"
                continue
            wordDict = {}
            for i in range(0,len(detail),2):
                try:
                    wordDict[detail[i].get_text().strip()]=detail[i+1].get_text().strip().replace("\n","")
                except:
                    break
            for key in wordDict.keys():
                if  '[' in key:
                    print wordDict[key].replace(" "*6,"")
                    continue
                print key+" "+wordDict[key]
            for i in sentence:
                print i.get_text()
            if  chinese!=None:
                print chinese.get_text()
if      __name__== "__main__":
        main()

python实现一个字典_第1张图片

你可能感兴趣的:(python)