python实现一个字典

本文介绍了一种使用Python的Selenium和BeautifulSoup库来爬取百度搜索结果中英文单词详细翻译信息的方法。该程序可以获取单词的释义、例句及中文翻译。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/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()

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值