#!/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实现一个字典
最新推荐文章于 2024-06-08 23:20:20 发布
本文介绍了一种使用Python的Selenium和BeautifulSoup库来爬取百度搜索结果中英文单词详细翻译信息的方法。该程序可以获取单词的释义、例句及中文翻译。
750

被折叠的 条评论
为什么被折叠?



