天天看點

python有道字典翻譯_使用python2爬取有道翻譯

爬蟲的核心思想:模拟浏覽器正常通路伺服器,一般情況隻要浏覽器能通路的,都可以爬,如果被反爬,則考慮反複測試添加Request Header資料,知道可以爬取為止。

反爬思路目前知道的有:User-Agent,Cookie,Referer,通路速度,驗證碼,使用者登入及前端js代碼驗證等。本例遇到js驗證 User-Agent Referer Cookie共計4種反爬機制。

關鍵部分是,參數headers和data的構造,headers要進行反複測試,data資料裡面的變量查找思路。

參考資料:

有道翻譯頁面,左邊輸入要翻譯的字元串,右邊會自動輸出翻譯的結果,如下圖

python有道字典翻譯_使用python2爬取有道翻譯

經過多次輸入字元測試,發現頁面無重新整理,猜測可能使用ajax,然後進行抓包分析,發現的确使用ajax傳輸資料

python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯
python有道字典翻譯_使用python2爬取有道翻譯

代碼如下:

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import urllib

import urllib2

import time

import hashlib

url = ‘http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule‘

keyword = raw_input(‘請輸入要翻譯的字元串: ‘)

# headers作用模拟浏覽器

headers = {

# "Accept": "application/json, text/javascript, */*; q=0.01",

# "Connection": "keep-alive",

# "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",

"Cookie": "你的浏覽器cookie值",

"Referer": "http://fanyi.youdao.com/",

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",

# "X-Requested-With": "XMLHttpRequest",

}

salt = str(int(time.time()*1000))

m = hashlib.md5()

str = "fanyideskweb" + keyword + salt + "ebSeFb%=XZ%T[KZ)c(sy!"

m.update(str)

sign = m.hexdigest().encode(‘utf-8‘)

print(sign)

# data為post請求資料

data = {

"i":keyword,

"from":"AUTO",

"to":"AUTO",

"smartresult":"dict",

"client":"fanyideskweb",

"salt":salt,

"sign":sign,

"doctype":"json",

"version":"2.1",

"keyfrom":"fanyi.web",

"action":"FY_BY_REALTIME",

"typoResult":"false"

}

# 對post上傳的資料進行urlencode編碼

data = urllib.urlencode(data)

# urllib 僅可以接受URL,不能建立 Request 類執行個體,也不能設定參數headers ,但可以對url進行編碼,而urllib2不能編碼,是以經常一起使用

# 而urllib2.urlopen(url)不能構造複雜的request,是以要使用urllib2.Request(url,data=data,headers=headers),2者都是有data參數時表示post送出資料,headers的值為模仿浏覽器請求頭裡面的的資料,格式為字典,讓伺服器接受的資料看起來像使用浏覽器通路。

request = urllib2.Request(url,data=data,headers=headers)

response = urllib2.urlopen(request)

print(response.read())

代碼測試,如下圖

python有道字典翻譯_使用python2爬取有道翻譯

原文位址:https://www.cnblogs.com/silence-cc/p/9193344.html