最近在爬SDFDA的數(shù)據(jù),剛開始用urllib.request 庫,一直連不到數(shù)據(jù) ;
后來通過CHROME瀏覽器的F12,發(fā)現(xiàn)該 網(wǎng)站用的是JSON格式{}'Content-Type': 'application/json',},不同于以往的提交方式“Content-Type: text/html; charset=utf-8"
試了各種方法 ,一直不能取得數(shù)據(jù)。
看的許多介紹方法中有用“requests”庫的,一試果然簡單方便,可以直接發(fā)送JSON格式的數(shù)據(jù)參數(shù);下載安裝后,導(dǎo)入“import resquest”
很快以往的問題得到解決,能將想要頁面內(nèi)容讀取出來,但顯示的是\u9882十六進制的編碼,沒有辦法繼續(xù)“百度”,
發(fā)現(xiàn)了requests庫中的,content 屬性和JSON屬性,一試果然見效;
查了下資料:
?
resp.text返回的是Unicode型的數(shù)據(jù)。?
resp.content返回的是bytes型的數(shù)據(jù)。?
也就是說,如果你想取文本,可以通過r.text。?
如果想取圖片,文件,則可以通過r.content。?
(resp.json()返回的是json格式數(shù)據(jù))
#-*- coding:utf-8 -*-
#讀取山東FDA的藥品GSP認(rèn)證經(jīng)營企業(yè)數(shù)據(jù)
# 20161128 zhangshaohua
import re
import requests
import json#讀取首頁
url = 'http://124.128.39.251:9080/sdfdaout/jsp/datasearch/searchinfolist.jsp?pageSize=10&entType=drugGSP&thisPage=1'
url = 'http://124.128.39.251:9080/sdfdaout/jsp/datasearch/searchinfolist.jsp?pageSize=10&thisPage=2&entType=drugGSP'
#url = 'http://124.128.39.251:9080/sdfdaout/jsp/datasearch/searchinfolist.jsp?pageSize=10&thisPage=12&entType=drugGSP'
#取總記錄數(shù),每頁20條#zjls = getContent(url,'共(\d{1,5})頁','UTF-8')
headers = {
'Host': '124.128.39.251:9080',
'Proxy-Connection': 'keep-alive',
'Content-Length': '256',
'Origin': 'http://124.128.39.251:9080',
'X-Requested-With': 'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'Content-Type': 'application/json',
'Accept': '*/*',
'Referer': 'http://124.128.39.251:9080/sdfdaout/jsp/datasearch/searchinfolist.jsp',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8',}url = 'http://124.128.39.251:9080/sdfdaout/command/ajax/com.lc.datasearch.cmd.SearchInfoQueryCmd'
parms = {"params":{"javaClass":"org.loushang.next.data.ParameterSet","map":{"limit":10,"start":10,"entType":"drugGSP","defaultSort":{"javaClass":"ArrayList","list":[]},"dir":"ASC","needTotal":True},"length":7},"context":{"javaClass":"HashMap","map":{},"length":0}}
values = json.dumps(parms)
req = requests.post(url,data=values,headers=headers)
content = req.json()print(content)print(type(content))print('藥品零售企業(yè)讀取完成!')
?
學(xué)習(xí)路上的坑還沒有完。
一直在PYTHON 客戶端中試的好好的,一到CMD執(zhí)行程序就變成了以上的提示;認(rèn)真對比了兩邊的代發(fā)現(xiàn):
content = req.json 和?
content = req.json()
帶()返回的是JSON的數(shù)據(jù),req.json 只返回類型為method 的一個提示;
轉(zhuǎn)載于:https://www.cnblogs.com/lrzy/p/6116482.html
總結(jié)
以上是生活随笔為你收集整理的python 3 关于requests库的 text / content /json的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。