【20171226】requests

requests是python第三方库,基于urllib,比urllib更方便,但更耗时,不能多线程运行

1、get请求

#coding=utf-8
import requests

# get请求,参数 params可以不带
getResponse = requests.get(url='http://dict.baidu.com/s', params={'wd':'python'})

print('请求url:',getResponse.url)
print('响应html:',getResponse.text)
print('响应内容二进制结果:',getResponse.content)
print('响应状态码:',getResponse.status_code)

2、post请求

1)普通post请求

#coding=utf-8
import requests

posturl = 'http://192.168.129.152:8090/queryRoadBookIdByRange.do'
postdata = {'longitude':'118.9','latitude':'31.8','cityName':'南京市','roadCount':'3'}

# 普通post请求
def post1():
    postResponse = requests.post(url=posturl, data=postdata)

    print('请求url:',postResponse.url)
    print('响应html:',postResponse.text)
    print('响应内容二进制结果:',postResponse.content)
    print('响应状态码:',postResponse.status_code)
post1()

2)post发送json

#coding=utf-8
import requests
import json

posturl = 'http://192.168.129.152:8090/queryRoadBookIdByRange.do'
postdata = {'longitude':'118.9','latitude':'31.8','cityName':'南京市','roadCount':'3'}

# post发送json
def post_json():
    postJsonResponse = requests.post(url=posturl, data=json.dumps(postdata))
    print(postJsonResponse.json())
post_json()

3)定制header

#coding=utf-8
import requests
import json

posturl = 'http://192.168.129.152:8090/queryRoadBookIdByRange.do'
postdata = {'longitude':'118.9','latitude':'31.8','cityName':'南京市','roadCount':'3'}

# 定制header
def post_header():
    data = {'some': 'data'}
    headers = {'content-type': 'application/json',
               'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}

    r = requests.post(url=posturl, data=postdata, headers=headers)
    print(r.text)
post_header()
原文地址:https://www.cnblogs.com/bxbyy/p/8127015.html