鱼C论坛

 找回密码
 立即注册
查看: 704|回复: 1

[作品展示] python爬百度翻译

[复制链接]
发表于 2023-7-26 22:52:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
今天总结一下爬翻译页面的过程和技巧,本人不是学前端和后端的技术人员,有些地方也不太懂。js就更不懂了
(等级不够,不能发图片)
第一步:
查看网页的结构(按F12)
查看网页的标头:主要是记录网页的请求连接和本机的Cookie(很重要,这个是模拟你本人的操作,防止网站的反爬)
查看负载:查看表单数据
(例如百度翻译)
from: en
to: zh
query: goods
transtype: realtime
simple_means_flag: 3
sign: 219044.504981
token: 3374a5e54805eacee8e4434b5638bb87
domain: common
ts: 1690292366583
这些都是你在post请求时网站核对的信息,一但那个参数不对就会禁止访问(现在反爬很严重)。

第二步
查看网页的源代码
寻找源代码的js的目录下的index文件
这一步主要是为了寻找表单数据中某些加密变量的算法。例如表单数据中的sign是一个加密的数
下面的步骤花了我一天的时间(本人不会前端)
1.ctrl f查找index文件下的sign变量
2.sign赋值这行设置断点,然后进行js调试,直到进入加密的函数(怎么调试自己查,我不细说)
3.把加密函数的js截断复制下来添加到你的文件目录里。


下面是我的js文件的内容。
大概就是以上步骤,我借鉴了很多网上的内容也学到了很多。


/****************************************************/
var r="320305.131321201";


function n(t, e) {
            for (var n = 0; n < e.length - 2; n += 3) {
                var r = e.charAt(n + 2);
                r = "a" <= r ? r.charCodeAt(0) - 87 : Number(r),
                r = "+" === e.charAt(n + 1) ? t >>> r : t << r,
                t = "+" === e.charAt(n) ? t + r & 4294967295 : t ^ r
            }
            return t
        }



kk=function (t) {
            var o, i = t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g);
            if (null === i) {
                var a = t.length;
                a > 30 && (t = "".concat(t.substr(0, 10)).concat(t.substr(Math.floor(a / 2) - 5, 10)).concat(t.substr(-10, 10)))
            } else {
                for (var s = t.split(/[\uD800-\uDBFF][\uDC00-\uDFFF]/), c = 0, u = s.length, l = []; c < u; c++)
                    "" !== s[c] && l.push.apply(l, function(t) {
                        if (Array.isArray(t))
                            return e(t)
                    }(o = s[c].split("")) || function(t) {
                        if ("undefined" != typeof Symbol && null != t[Symbol.iterator] || null != t["@@iterator"])
                            return Array.from(t)
                    }(o) || function(t, n) {
                        if (t) {
                            if ("string" == typeof t)
                                return e(t, n);
                            var r = Object.prototype.toString.call(t).slice(8, -1);
                            return "Object" === r && t.constructor && (r = t.constructor.name),
                            "Map" === r || "Set" === r ? Array.from(t) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? e(t, n) : void 0
                        }
                    }(o) || function() {
                        throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
                    }()),
                    c !== u - 1 && l.push(i[c]);
                var p = l.length;
                p > 30 && (t = l.slice(0, 10).join("") + l.slice(Math.floor(p / 2) - 5, Math.floor(p / 2) + 5).join("") + l.slice(-10).join(""))
            }
            for (var d = "".concat(String.fromCharCode(103)).concat(String.fromCharCode(116)).concat(String.fromCharCode(107)), h = (null !== r ? r : (r = window[d] || "") || "").split("."), f = Number(h[0]) || 0, m = Number(h[1]) || 0, g = [], y = 0, v = 0; v < t.length; v++) {
                var _ = t.charCodeAt(v);
                _ < 128 ? g[y++] = _ : (_ < 2048 ? g[y++] = _ >> 6 | 192 : (55296 == (64512 & _) && v + 1 < t.length && 56320 == (64512 & t.charCodeAt(v + 1)) ? (_ = 65536 + ((1023 & _) << 10) + (1023 & t.charCodeAt(++v)),
                g[y++] = _ >> 18 | 240,
                g[y++] = _ >> 12 & 63 | 128) : g[y++] = _ >> 12 | 224,
                g[y++] = _ >> 6 & 63 | 128),
                g[y++] = 63 & _ | 128)
            }
            for (var b = f, w = "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(97)) + "".concat(String.fromCharCode(94)).concat(String.fromCharCode(43)).concat(String.fromCharCode(54)), k = "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(51)) + "".concat(String.fromCharCode(94)).concat(String.fromCharCode(43)).concat(String.fromCharCode(98)) + "".concat(String.fromCharCode(43)).concat(String.fromCharCode(45)).concat(String.fromCharCode(102)), x = 0; x < g.length; x++)
                b = n(b += g[x], w);
            return b = n(b, k),
            (b ^= m) < 0 && (b = 2147483648 + (2147483647 & b)),
            "".concat((b %= 1e6).toString(), ".").concat(b ^ f)
}

/****************************************************/

import requests
import os
import re
import time
import random
import execjs

#定义你自己存放的js的目录位置
os.chdir('d://ppt')


class baiduSpider(object):
    def __init__(self):

        self.url='填写网页url'
        self.headers={
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
        "Cookie":'填写自己的网页cookie'
        }

    def attack_yd(self,word):
        #构建form表单数据
        with open('baidusign.js', 'r', encoding='utf-8') as f:
            ctx = execjs.compile(f.read())
            sign = ctx.call('kk', word)#返回js编译的结果 word是参数
        data={
            "query": word,
            "from": "en",
            "to": "zh",
            "domain": "common",
            "token":'3374a5e54805eacee8e4434b5638bb87',
            "simple_means_flag":3,
            "sign":sign,  #sign是一个加密的数,根据word和函数计算得出,具体看百度翻译的js内容
        }
        #使用 reqeusts.post()方法提交请求
        res = requests.post(
            url=self.url,
            data=data,
            headers=self.headers,
        )
        # res.json() 将json格式的字符串转为python数据类型
        # 客户端与服务器数据交互以json字符串传递,因此需要将它转换为python数据类型
        html=res.json()
        print(html)
        #{'trans_result': {'data': [{'dst': '是', 'src': 'are'}],翻译格式
        result=html['trans_result']['data'][0]["dst"]
        print('翻译结果:', result)
    def run(self):
        try:
            word=input('请输入要翻译的单词:')
            self.attack_yd(word)
        except Exception as e:
            print(e)
if __name__ == '__main__':
    spider=baiduSpider()
    spider.run()
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-7-26 22:56:22 | 显示全部楼层
图片可以上传至图床:imgtp.com

然后选择 ubb,直接粘贴到论坛编辑器里

Snipaste_2023-07-26_22-55-53.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 07:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表