[Python爬蟲筆記][隨意找個博客入門(一)]
標簽(空格分隔): Python 爬蟲 2016年暑假
來源博客:掙脫不足與蒙昧
1.簡單的爬取特定url的html代碼
import urllib.request
url = "http://120.27.101.158/"
response = urllib.request.urlopen(url)
html = response.read()
html = html.decode('utf-8');
print (html)
urllib.request.urlopen()- 有點類似於文件操作里的open,返回的
response對象也類似與文件對象。 - 等價於
req = urllib.request.Request("http://placekitten.com/500/600") response = urllib.request.urlopen(req)
- 有點類似於文件操作里的open,返回的
response.read()response對象的讀操作,類似的文件對象的讀操作.- 該對象還有以下常用方法
response.geturl() ##訪問的具體地址。 response.info() ##遠程的服務器的信息 response.getcode() ##http的狀態
html.decode()- decode() 方法以encoding指定的編碼格式解碼字符串。
2.簡單的翻譯程序(爬取有道詞典)
- 在我們注冊信息的時候,填寫資料的時候,都涉及到表單(form)的應用。 是一個POST請求發送到服務器端的過程。 HTML中的表單時有特定格式的,舉個例子,我們打開有道在線翻譯,調出調試平台,輸入翻譯內容“Hello,Python”點擊自動翻譯。

- 在調試平台中的
network中我們可以看到一些常見的信息 - 如訪問的具體的
url地址,http的狀態(200)

- 在參數欄(FireFox)可以看見提交的表單信息(
json格式)

- 在響應欄,可以知道返回的表單信息也是
json格式
用字典傳入一個json並提交表單,並解析返回來html里的json,代碼如下。
import urllib.request
'''urllib中的parse用來對url解析'''
import urllib.parse
import json
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null/'
content = input("你想翻譯什么呀?")
data = {}
data['type']='AUTO'
data['i'] = content
data['doctype'] = 'json'
data['xmlVersion'] = '1.8'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url, data)
html=response.read().decode('utf-8')
target =json.loads(html)
print ("翻譯結果是:%s" %(target['translateResult'][0][0]['tgt']))
結果
> print (target)
{'translateResult': [[{'src': '測試程序', 'tgt': 'The test program'}]], 'elapsedTime': 0, 'errorCode': 0, 'smartResult': {'entries': ['', '[計] test program'], 'type': 1}, 'type': 'ZH_CN2EN'}
我們看到翻譯的內容在translateResult[0][0][‘tgt’]中

-
data = urllib.parse.urlencode(data).encode('utf-8')-
將字典轉換為能夠
post,get進行的字符串,對於中文編碼為默認格式的字符串。 -
encode將該字符串轉換為一個字節序列。(從下面程序可以看出其實這個utf-8沒什么卵用,換成gbk還會是一樣的結果)
data
{'type': 'AUTO', 'ue': 'UTF-8', 'typoResult': 'true', 'i': '程序測試', 'xmlVersion': '1.8', 'keyfrom': 'fanyi.web', 'doctype': 'json'}
data = urllib.parse.urlencode(data); #dict轉換為str
'type=AUTO&ue=UTF-8&typoResult=true&i=%E7%A8%8B%E5%BA%8F%E6%B5%8B%E8%AF%95&xmlVersion=1.8&keyfrom=fanyi.web&doctype=json'
data = data.encode('utf-8'); #str轉換為byte序列
b'type=AUTO&ue=UTF-8&typoResult=true&i=%E7%A8%8B%E5%BA%8F%E6%B5%8B%E8%AF%95&xmlVersion=1.8&keyfrom=fanyi.web&doctype=json' -
-
response = urllib.request.urlopen(url, data)- 傳入的
data必須為byte型字符串
- 傳入的
-
html=response.read().decode('utf-8')- 將接收來的
utf-8頁面解碼為unicode
- 將接收來的
-
target =json.loads(html)- 這個頁面應該是一個
json,將其轉換為字典
- 這個頁面應該是一個
3.小模仿,爬谷歌翻譯
import re
import urllib.parse
import urllib.request
#----------模擬瀏覽器的行為,向谷歌翻譯發送數據,然后抓取翻譯結果,這就是大概的思路-------
def Gtranslate(text):
Gtext=text #text 輸入要翻譯的英文句子
#hl:瀏覽器、操作系統語言,默認是zh-CN
#ie:默認是UTF-8
#text:就是要翻譯的字符串
#langpair:語言對,即'en'|'zh-CN'表示從英語到簡體中文
values={'hl':'zh-CN','ie':'UTF-8','text':Gtext,'langpair':"auto"}
url='http://translate.google.cn/' #URL用來存儲谷歌翻譯的網址
data = urllib.parse.urlencode(values).encode("utf-8") #將values中的數據通過urllib.urlencode轉義為URL專用的格式然后賦給data存儲
req = urllib.request.Request(url,data) #然后用URL和data生成一個request
browser='Mozilla/4.0 (Windows; U;MSIE 6.0; Windows NT 6.1; SV1; .NET CLR 2.0.50727)' #偽裝一個IE6.0瀏覽器訪問,如果不偽裝,谷歌將返回一個403錯誤
req.add_header('User-Agent',browser)
response = urllib.request.urlopen(req) #向谷歌翻譯發送請求
html=response.read() #讀取返回頁面,然后我們就從這個HTML頁面中截取翻譯過來的字符串即可
html=html.decode('utf-8')
#使用正則表達式匹配<=TRANSLATED_TEXT=)。而翻譯后的文本是'TRANSLATED_TEXT='等號后面的內容
p=re.compile(r"(?<=TRANSLATED_TEXT=).*(?=';INPUT_TOOL_PATH='//www.google.com')")
m=p.search(html)
chineseText=m.group(0).strip(';')
return chineseText
if __name__ == "__main__":
#Gtext為待翻譯的字符串
Gtext='我是上帝'
print('The input text: %s' % Gtext)
chineseText=Gtranslate(Gtext).strip("'")
print('Translated End,The output text: %s' % chineseText)
-
實際的爬蟲十分麻煩,要考慮是否被屏蔽,還有登陸等等問題。待繼續好好學習。
-
幾個資料
Python網絡爬蟲(Get、Post抓取方式)
py爬取英文文檔學習單詞
python網絡爬蟲入門(二)——用python簡單實現調用谷歌翻譯
