Python crawler actual combat, requests+random module, Python makes desktop translation software

foreword

Try making translation software in Python today. Here to provide the code for the friends who need it, and give some tips.

The function of the program is very simple, you can choose any translator from the three mainstream translators to translate words and sentences, use the PyQt5 module to realize human-computer interaction, use the requests module to send requests, and return the translation results to the user.

insert image description here

development tools

Python version: 3.8

Related modules:

requests module
re module
time module
js2py module
random module
hashlib module

Environment build

Install Python and add it to the environment variable, and pip installs the required related modules.

Idea analysis

The function of the program is very simple, you can choose any translator from the three mainstream translators to translate words and sentences, use the PyQt5 module to realize human-computer interaction, use the requests module to send requests, and return the translation results to the user.

Implementation

Take baidu translation as an example

Translate arbitrarily to view page information.
insert image description here
It can be seen from the picture that this is a post request, and the data of the request header is also clearly displayed in the picture.

request header

Code


'''
User-Agent和Cookie 需要自行添加
Token中的T换成小写t
Function:
	翻译类
'''
class baidu():
	def __init__(self):
		self.session = requests.Session()
		self.session.cookies.set('BAIDUID', '19288887A223954909730262637D1DEB:FG=1;')
		self.session.cookies.set('PSTM', '%d;' % int(time.time()))
		self.headers = {
    
    
							'User-Agent': 'XXX'
						}
		self.data = {
    
    
						'query': '',
						'simple_means_flag': '3',
						'sign': '',
						'Token': '',
					}
		self.url = 'https://fanyi.baidu.com/v2transapi'
	def translate(self, word):
		self.data['query'] = word
		self.data['token'], gtk = self.getTokenGtk()
		self.data['token'] = '6482f137ca44f07742b2677f5ffd39e1'
		self.data['sign'] = self.getSign(gtk, word)
		res = self.session.post(self.url, data=self.data)
		return [res.json()['trans_result']['data'][0]['result'][0][1]]
	def getTokenGtk(self):
		url = 'https://fanyi.baidu.com/'
		res = requests.get(url, headers=self.headers)
		token = re.findall(r"token: '(.*?)'", res.text)[0]
		gtk = re.findall(r";window.gtk = ('.*?');", res.text)[0]
		return token, gtk
	def getSign(self, gtk, word):
		evaljs = js2py.EvalJs()
		js_code = js.bd_js_code
		js_code = js_code.replace('null !== i ? i : (i = window[l] || "") || ""', gtk)
		evaljs.execute(js_code)
		sign = evaljs.e(word)
		return sign

Graphical interface code implementation

class Demo(QWidget):
	def __init__(self, parent=None):
		super().__init__()
		self.setWindowTitle('翻译软件-公众号: Python工程狮')
		self.Label1 = QLabel('原文')
		self.Label2 = QLabel('译文')
		self.LineEdit1 = QLineEdit()
		self.LineEdit2 = QLineEdit()
		self.translateButton1 = QPushButton()
		self.translateButton2 = QPushButton()
		self.translateButton3 = QPushButton()
		self.translateButton1.setText('baidu翻译')
		self.translateButton2.setText('youdao翻译')
		self.translateButton3.setText('Google翻译')
		self.grid = QGridLayout()
		self.grid.setSpacing(12)
		self.grid.addWidget(self.Label1, 1, 0)
		self.grid.addWidget(self.LineEdit1, 1, 1)
		self.grid.addWidget(self.Label2, 2, 0)
		self.grid.addWidget(self.LineEdit2, 2, 1)
		self.grid.addWidget(self.translateButton1, 1, 2)
		self.grid.addWidget(self.translateButton2, 2, 2)
		self.grid.addWidget(self.translateButton3, 3, 2)
		self.setLayout(self.grid)
		self.resize(400, 150)
		self.translateButton1.clicked.connect(lambda : self.translate(api='baidu'))
		self.translateButton2.clicked.connect(lambda : self.translate(api='youdao'))
		self.translateButton3.clicked.connect(lambda : self.translate(api='google'))
		self.bd_translate = baidu()
		self.yd_translate = youdao()
		self.gg_translate = google()
	def translate(self, api='baidu'):
		word = self.LineEdit1.text()
		if not word:
			return
		if api == 'baidu':
			results = self.bd_translate.translate(word)
		elif api == 'youdao':
			results = self.yd_translate.translate(word)
		elif api == 'google':
			results = self.gg_translate.translate(word)
		else:
			raise RuntimeError('Api should be <baidu> or <youdao> or <google>...')
		for result in results:
			self.LineEdit2.setText(result)

at last

In order to thank the readers, I would like to share with you some of my recent favorite programming dry goods, to give back to every reader, and hope to help you.

There is a full set of information suitable for beginners~

Come and grow up with Xiaoyu!

① More than 100+ Python e-books (mainstream and classic books should be available)

② Python standard library information (the most complete Chinese version)

③ Source code of reptile projects (forty or fifty interesting and classic hand-practicing projects and source codes)

④ Videos on basics of Python, crawlers, web development, and big data analysis (suitable for beginners)

⑤ Python Learning Roadmap (Farewell to Influential Learning)

material

Guess you like

Origin blog.csdn.net/Modeler_xiaoyu/article/details/128207873