作为一位python小白,无意间发现在jclian91发布的博客中做了个爬取有道词典的翻译爬虫,本着学习的态度,借鉴大佬的代码,自己也撸了串代码,完成了自己的第一个爬虫代码,添加了gui界面,添加了从汉翻英的功能。
代码中用到的第三方库自行通过pip install
安装
代码如下:
#! python3
# -*- coding: UTF-8 -*-
# Author:fan liu
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import re
import wx
class MyFrame(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,title='translate',size=(410,335))
bkg=wx.Panel(self)
self.Btn1=wx.Button(bkg,label='中文翻译')
self.Btn1.Bind(wx.EVT_BUTTON,self.ch_trans)
self.Btn3=wx.Button(bkg,label='英文翻译')
self.Btn3.Bind(wx.EVT_BUTTON,self.eng_trans)
self.Btn2=wx.Button(bkg,label='清除')
self.Btn2.Bind(wx.EVT_BUTTON,self.clear)
self.word=wx.TextCtrl(bkg)
self.contents=wx.TextCtrl(bkg,style=wx.TE_MULTILINE|wx.HSCROLL)
self.hbox=wx.BoxSizer()
self.hbox.Add(self.word,proportion=1,flag=wx.EXPAND)
self.hbox.Add(self.Btn1,proportion=0,flag=wx.LEFT,border=5)
self.hbox.Add(self.Btn3,proportion=0,flag=wx.LEFT,border=5)
self.hbox.Add(self.Btn2,proportion=0,flag=wx.LEFT,border=5)
self.vbox=wx.BoxSizer(wx.VERTICAL)
self.vbox.Add(self.hbox,proportion=0,flag=wx.EXPAND | wx.ALL,border=5)
self.vbox.Add(self.contents,proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,border=5)
bkg.SetSizer(self.vbox)
def ch_trans(self,event):
word=self.word.GetValue()
ua=UserAgent()
headers={'User-Agent':ua.random}
try:
string=''
string1=''
r=requests.get(url='http://dict.youdao.com/w/%s/#keyfrom=dict2.top'%word,headers=headers)
soup=BeautifulSoup(r.text,'lxml')
s=soup.find(class_="trans-container")('ul')[0]('p')
for item in s:
if item.text:
string=str(item.text)
li=re.split('[\n]+',string)
for i in li:
string1+=i
string1+='\n'
self.contents.SetValue(string1)
except Exception:
self.contents.SetValue('something goes wrong!')
def eng_trans(self,event):
word=self.word.GetValue()
ua=UserAgent()
headers={'User-Agent':ua.random}
try:
r=requests.get(url='http://dict.youdao.com/w/%s/#keyfrom=dict2.top'%word,headers=headers)
soup=BeautifulSoup(r.text,'lxml')
s=soup.find(class_="trans-container")('ul')[0]('li')
string=''
for item in s:
if item.text:
string+=str(item.text)+'\n'
self.contents.SetValue(string)
except Exception:
self.contents.SetValue('something goes wrong!')
def clear(self,event):
self.word.SetValue('')
self.contents.SetValue('')
if __name__=='__main__':
app=wx.App()
frame=MyFrame(None,-1)
frame.Show()
app.MainLoop()