python學習筆記,使用爬蟲用有道進行翻譯

2021-10-03 20:39:39 字數 1236 閱讀 8422

使用爬蟲使用有道進行翻譯

import urllib.request

import urllib.parse #匯入轉義傳入response中的data型別

import json

content=

input

("請輸入需要翻譯的內容:"

)url=

""data=

data[

'i']

= content

data[

'from']=

'auto'

data[

'to']=

'auto'

data[

'smartresult']=

'dict'

data[

'client']=

'fanyideskweb'

data[

'doctype']=

'json'

data[

'version']=

'2.1'

data[

'keyfrom']=

'fanyi.web'

data[

'action']=

'fy_by_realtlme'

data=urllib.parse.urlencode(data)

.encode(

'utf-8'

)#使用parse對data進行轉義,在把data轉為utf-8的形式

response=urllib.request.urlopen(url,data)

html=response.read(

).decode(

'utf-8'

)#意思就是把頁面中讀取的資料轉義為utf-8的編碼形式

'''print(html)

>>>]]}

這一串相當於乙個字段,使用json.loads放在target中,然後使用鍵找到translateresult中的翻譯結果

'''target = json.loads(html)

print

("翻譯結果:%s"

%(target[

'translateresult'][

0][0

]['tgt'])

)

結果:

請輸入需要翻譯的內容:我愛中國

翻譯結果:i love china

python爬蟲學習筆記

一 爬蟲思路 對於一般的文章而言,思路如下 1.通過主頁url獲取主頁原始碼,從主頁原始碼中獲得 標題 鏈結 如想要抓取知乎上的新聞,就獲得主頁上的新聞鏈結 2.繼續通過 標題 鏈結獲得 標題 原始碼,進而獲得 標題 中的內容。其中,當存在多頁時,先將每一頁都一樣的url寫下來,然後迴圈加入頁碼,具...

Python爬蟲學習筆記

1.使用build opener 修改報頭 headers user agent 定義變數headers儲存user agent資訊 opener urllib.request.build opener 建立opener物件並賦給變數 openeropener.addheaders headers ...

python爬蟲學習筆記

2.網頁資訊提取 beautiful soup庫 這是 學習北理的嵩山天老師mooc教程的筆記,是老師上課用的例項。import requests url try kv 將爬蟲偽裝成瀏覽器 r requests.get url,headers kv r.raise for status print ...