pang2016 pang2016 - 22 days ago 8
Python Question

requests.session post error 'dict' object has no attribute 'read'

this is my first useage of session.post I analog mobile browser to crawl a website.

http://m.ctrip.com/webapp/hotel/hoteldetail/dianping/419302.html?roomtype=&opr=&fr=detail&daylater=0&days=1

this is the headers:
enter image description here

the codes´╝Ü

import requests
from bs4 import BeautifulSoup
import json

session=requests.Session()
headers={
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'}

data={
"flag":1,"id":"419302","htype":1,"sort":{"idx":4,"size":10,"sort":2,"ord":1},
"search":{"kword":"","gtype":4,"opr":0,"ctrl":14,"filters":[]},"alliance":{"aid":"4897","sid":"130026","ouid":"","ishybrid":0},
"Key":"b2d4a14cd19fa0e656d35f065bdcdd16",
"head":{"cid":"09031140210396054230","ctok":"","cver":"1.0","lang":"01","sid":"8888","syscode":"09","auth":None,"extension":
[{"name":"pageid","value":"228032"},{"name":"webp","value":1},{"name":"referrer","value":"http://www.ctrip.com/"},{"name":"protocal","value":"http"}]},
"contentType":"json"}
url='http://m.ctrip.com/restapi/soa2/10soup.text935/hotel/booking/commentgroupsearch?_fxpcqlniredt=09031140210396054230'
soup=session.post(url,headers=headers,files=data)
print soup


the error:

'dict' object has no attribute 'read'

Answer

You want to convert your data dict to a string, then send it using the data= parameter of session.post():

soup = session.post(url, headers=headers, data=json.dumps(data))

Or, if you are using requests version 2.4.2 or newer, you can pass your dict directly using the json= parameter:

soup = session.post(url, headers=headers, json=data)

Check your requests version with requests.__version__.

Comments