requests
Posted holaworld
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了requests相关的知识,希望对你有一定的参考价值。
import requests
def gethtmlText(url):
try:
kv = {'user-agent':'Mozilla/5.0'}
r = requests.get(url, timeout=30, headers=kv)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
print(r.request.headers)
print('---------------')
return r.text[:1000]
except:
return '产生异常'
if __name__ == '__main__':
url = 'http://www.baidu.com'
print(getHTMLText(url))
import requests
def search(url,keyword):
try:
kv = {'wd':keyword}
r = requests.get(url, params=kv)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
print(r.request.url)
print('---------------')
return r.text[:1000]
except:
return '爬取失败'
if __name__ == '__main__':
url = 'http://www.baidu.com/s'
keyword = '搜索的内容'
print(search(url,keyword))
import requests
def saveImg(url,path):
try:
r = requests.get(url)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
with open(path,'wb') as f:
f.write(r.content)
f.close()
return '保存成功'
except:
return '爬取失败'
if __name__ == '__main__':
url = 'https://www.baidu.com/'
path = 'C://za//temp.jpg'
print(saveImg(url,path))
以上是关于requests的主要内容,如果未能解决你的问题,请参考以下文章
C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段
Motan在服务provider端用于处理request的线程池
[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段