这几天在爬了Python的官方文档,但是它里面全是英文,只有数字,没有汉字,原谅我这个英语渣渣搞不懂,只能靠翻译了,如果是复制到百度翻译的话太慢,耗时间。所以就直接用爬虫来搞了,自动化翻译文档
这是百度翻译的页面
刚开始想用urllib去做,但是给我报了一个我的浏览器版本太低了,估计就是得加headers和UA。太麻烦了,就想到了selenium,直接用selenium妥妥的,下面就是详细步骤了。
先从爬Python官网开始吧
就只抓了这一页的数据。这个简单,直接可以使用requests或者urllib抓取,然后转换成pdf。我的是在框架里面,有点麻烦,如果你觉得麻烦可以直接请求。
安装Python库:pip3 install pdfkit
安装插件wkhtmltopdf,
https://wkhtmltopdf.org/downloads.html官网地址
importscrapy
importpdfkit
classso_python3_spider(scrapy.Spider):
name = 'doc'defstart_requests(self):
url = 'https://docs.python.org/3.8/whatsnew/3.8.html'yieldscrapy.Request(url=url,callback=self.parse)
defparse(self,response):
body = response.selector.xpath('//div[@class="section"]').extract()
title = response.selector.xpath('//div[@class="section"]/h1/text()').extract()
html_template = """
{content}"""fori inrange(len(body)):html = html_template.format(content=body[i])
withopen(title[i]+'.html','a',encoding='utf8') asf:
f.write(html)
options = {
'page-size': 'Letter','encoding': "UTF-8",'custom-header': [
('Accept-Encoding','gzip')
]
}
path_wk = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'#安装位置config = pdfkit.configuration(wkhtmltopdf=path_wk)
pdfkit.from_file(title[i]+'.html',title[i]+'.pdf',options=options,configuration=config)
我是直接将一个div里面的这个内容全部拿下来,然后拼接一个新的html,将这个新的HTML转换成PDF。
第二阶段就是打开这个pdf,读取该文档,将其发送到百度翻译的框框,获取翻译的结果,重新保存
-----------读取文档--------
defread_pdf_to_text(self):
fp = open("What’s New In Python 3.8.pdf","rb") #根据二进制的方式读取#如果是url# fp=request.urlopen(url)#网址#创建与文档关联的解释器parser = PDFParser(fp)
#创建一个pdf文档对象doc = PDFDocument()
#连接解释器和文档对象parser.set_document(doc)
doc.set_parser(parser)
#对文档进行初始化doc.initialize("") #文件没有密码就是空字符串#创建一个pdf资源管理器resouse = PDFResourceManager()
#创建一个参数分析器lap = LAParams()
#创建一个聚合器device = PDFPageAggregator(resouse,laparams=lap)
#创建一个页面解释器interpreter = PDFPageInterpreter(resouse,device)
#开始读取内容forpage indoc.get_pages():
#调用页面解释器来解释interpreter.process_page(page)
#使用聚合器来获得内容layout = device.get_result()
forout inlayout:
ifhasattr(out,"get_text"):
content = out.get_text()
将文档读取,发送到百度翻译https://fanyi.baidu.com/?aldtype=16047#en/zh
找到输入框和输出框的位置
翻译模块(复制到微信里,格式有点问题,大家自己修正)
defbaidu_fanyi(self,content):
time.sleep(5)
#找到输入框的位置,并将内容发送到该位置self.browser.find_element_by_id('baidu_translate_input').send_keys(content)
time.sleep(5)
#获取输出框的内容con = self.browser.find_element_by_class_name('output-bd')
#写入文件withopen('python3.8.txt','a',encoding='utf8') asf:
#由于content内容带有回车符,所以不用\nf.write(content + con.text + '\n')
#将输入框清空,等待下一次输入self.browser.find_element_by_id('baidu_translate_input').clear()
time.sleep(5)
这是翻译后输出的内容
当然还有可以优化加强的部分,比如使用pyqt做个界面,打包成exe就可以当程序用了。有什么建议留言。
完整代码回复 ‘翻译‘ 获取,这里就不放了,太长了。觉得还不错的点个赞,有什么问题可以留言问我,或者直接在公众号中发消息,都可以。