1. 程式人生 > >Python爬蟲【實戰篇】百度翻譯

Python爬蟲【實戰篇】百度翻譯

先看程式碼

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
data = {
    "from":"en",
    "to":"zh",
    "query":"student",
    "transtype":"translang",
    "simple_means_flag":"
3", "sign":"372549.85108", "token":"e89a8f037aac1b51a86cbc82356949d" } post_url = "http://fanyi.baidu.com/v2transapi" r = requests.post(post_url,data=data,headers=headers) print(r.content.decode())

從程式碼中可以看到,所攜帶的請求引數比較多,可以嘗試切換成手機模式進行請求。

import requests

headers = {
    "User-Agent
": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1" } data = { "query": "學生", "from": "zh", "to": "en" } response = requests.post(url='https://fanyi.baidu.com/basetrans', headers=headers, data=data) response
= response.content.decode('utf-8') print(type(response)) import json response = json.loads(response) print(response.get("trans")[0].get("dst"))

可以很清楚的看到,手機模式所攜帶的引數比較少,如果我們以後遇到電腦請求攜帶的引數比較多,可以切換成手機模式來進行請求,會更加容易