python3爬虫初探(八)requests

来源:转载




几个常见的操作:


import requests
#from PIL import Image
#from io import BytesIOdef simple_get(url):
resp = requests.get(url)
print(resp.status_code)
print(resp.encoding)
print(resp.text)def get_with_parameters(url):
resp = requests.get(url, params={'key1':'你好', 'key2':'世界'})
print(resp.url)
print(resp.text)

def get_with_ua(url):
ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
resp = requests.get(url, headers={'user-agent':ua})
# print(resp.text)
# print(resp.headers)
jdata = resp.json()
print(jdata['headers']['User-Agent'])

def get_using_cookie(url):
resp = requests.get(url, cookies={'key1':'hello', 'key2':'world'})
for k, v in resp.cookies.items():
print(k, v)
'''
def get_image(url):
resp = requests.get(url)
image = Image.open(BytesIO(resp.content))
image.save('sample.jpg')
'''
simple_get('http://httpbin.org/get')
# get_with_parameters('http://httpbin.org/get')
# get_with_ua('http://httpbin.org/get')
# get_using_cookie('http://www.baidu.com')
#get_image('http://n.sinaimg.cn/news/1_img/cfp/c4b46437/20171009/wZwz-fymrcpu8452587.jpg')





分享给朋友:
您可能感兴趣的文章:
随机阅读: