鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python  HTML/ python 非常簡單爬蟲問題

python 非常簡單爬蟲問題

'''
parse 模擬 post
分析百度翻譯
1:打開網(wǎng)頁源代碼
2:輸入girl,輸入一個letter有一個request
3:請求地址:http://fanyi.baidu.com/sug
4:發(fā)現(xiàn)formdata kw:girl
5:return 格式是 json==> need package json
'''


from urllib import parse,request
#manage json moudel

import json

'''
1:data 構(gòu)造,然后urlopen打開
2:返回json style result
3:encode 'girl'
'''
baseurl = 'http://fanyi.baidu.com/sug'

# 存放form ==> dict style


data ={
    'ke':'girl'
}


#enode

data =parse.urlencode(data).encode('utf-8')#type -bytes
##encode string in 'utf-8'style== change style to bytes ,not change content


#request headed (include data_lenth)

headers={
    # post need content-lenth
    'Content-Lengh':len(data)

}

# we have request header ,try request
req=request.Request(url=baseurl,data=data,headers=headers)

rsp=request.urlopen(req)
json_data= rsp.read().decode('utf-8')

print(type(json_data))#str

#change style str to dict

json_data=json.loads(json_data)

print(type(json_data))#dict
print(json_data)


圖片描述

回答
編輯回答
淚染裳
import requests
import json

url = 'http://fanyi.baidu.com/sug'
data = {'kw':'girl'}
res = requests.post(url, data=data)
content = json.loads(res.content.decode())
print(content)

圖片描述

2017年11月13日 17:08