最近在爬SDFDA的數據,剛開始用urllib.request 庫,一直連不到數據 ;
后來通過CHROME瀏覽器的F12,發現該 網站用的是JSON格式{}'Content-Type': 'application/json',},不同于以往的提交方式“Content-Type: text/html; charset=utf-8"
試了各種方法 ,一直不能取得數據。
看的許多介紹方法中有用“requests”庫的,一試果然簡單方便,可以直接發送JSON格式的數據參數;下載安裝后,導入“import resquest”
很快以往的問題得到解決,能將想要頁面內容讀取出來,但顯示的是\u9882十六進制的編碼,沒有辦法繼續“百度”,
發現了requests庫中的,content 屬性和JSON屬性,一試果然見效;
查了下資料:
?
resp.text返回的是Unicode型的數據。?
resp.content返回的是bytes型的數據。?
也就是說,如果你想取文本,可以通過r.text。?
如果想取圖片,文件,則可以通過r.content。?
(resp.json()返回的是json格式數據)
#-*- coding:utf-8 -*-
#讀取山東FDA的藥品GSP認證經營企業數據
# 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'
#取總記錄數,每頁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('藥品零售企業讀取完成!')
?
學習路上的坑還沒有完。
一直在PYTHON 客戶端中試的好好的,一到CMD執行程序就變成了以上的提示;認真對比了兩邊的代發現:
content = req.json 和?
content = req.json()
帶()返回的是JSON的數據,req.json 只返回類型為method 的一個提示;
轉載于:https://www.cnblogs.com/lrzy/p/6116482.html
總結
以上是生活随笔為你收集整理的python 3 关于requests库的 text / content /json的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。