python requests
比urllib.request更方便的爬虫工具
官方中文文档:http://cn.python-requests.org/zh_CN/latest/
安装
1 2 3 | pip install requests # 或者用pycharm点点点 |
导入模块
1 | >>> import requests |
网页的基本用法,GET,POST,PUT,DELETE,HEAD,OPTIONS
1 2 3 4 5 6 | >>> r = requests.get( 'https://api.github.com/events' ) >>> r = requests.post( 'http://httpbin.org/post' , data = { 'key' : 'value' }) >>> r = requests.put( 'http://httpbin.org/put' , data = { 'key' : 'value' }) >>> r = requests.delete( 'http://httpbin.org/delete' ) >>> r = requests. head ( 'http://httpbin.org/get' ) >>> r = requests.options( 'http://httpbin.org/get' ) |
传递URL参数,url+问号+键值对,例如http://httpbin.org/get?key2=value2&key1=value1
get请求使用params参数
post请求使用data参数
1 2 3 4 5 6 7 8 9 10 11 | >>> payload = { 'key1' : 'value1' , 'key2' : 'value2' } >>> r = requests.get( "http://httpbin.org/get" , params = payload) >>> print (r.url) http: / / httpbin.org / get?key2 = value2&key1 = value1 #注意字典里值为 None 的键都不会被添加到 URL 的查询字符串里。 #还可以将一个列表作为值传入: >>> payload = { 'key1' : 'value1' , 'key2' : [ 'value2' , 'value3' ]} >>> r = requests.get( 'http://httpbin.org/get' , params = payload) >>> print (r.url) http: / / httpbin.org / get?key1 = value1&key2 = value2&key2 = value3 |
文本类型响应内容
1 2 3 4 5 6 7 8 9 10 | #Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。 >>> import requests >>> r = requests.get( 'https://api.github.com/events' ) >>> r.text u'[{ "repository" :{ "open_issues" : 0 , "url" :"https: / / github.com / ... #请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它。如果改变了编码,每当访问 r.text ,Request 都将会使用 r.encoding 的新值。 >>> r.encoding 'utf-8' >>> r.encoding = 'gb2312' |
二进制响应内容
1 2 | >>> r.content b'[{ "repository" :{ "open_issues" : 0 , "url" :"https: / / github.com / ... |
JSON响应内容
1 2 | >>> r.json() [{u 'repository' : {u 'open_issues' : 0 , u 'url' : 'https: / / github.com / ... |
定制请求头
1 2 3 | >>> url = 'https://api.github.com/some/endpoint' >>> headers = { 'user-agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' } >>> r = requests.get(url, headers = headers) |
响应状态码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | >>> r = requests.get( 'http://httpbin.org/get' ) >>> r.status_code 200 #为方便引用,Requests还附带了一个内置的状态码查询对象 >>> r.status_code = = requests.codes.ok True #如果发送了一个错误请求4XX,5XX,还可以抛出异常 >>> bad_r = requests.get( 'http://httpbin.org/status/404' ) >>> bad_r.status_code 404 >>> bad_r.raise_for_status() Traceback (most recent call last): File "requests/models.py" , line 832 , in raise_for_status raise http_error requests.exceptions.HTTPError: 404 Client Error #当状态码是200时 >>> r.raise_for_status() None |
响应头
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | >>> r.headers { 'content-encoding' : 'gzip' , 'transfer-encoding' : 'chunked' , 'connection' : 'close' , 'server' : 'nginx/1.0.4' , 'x-runtime' : '148ms' , 'etag' : '"e1ca502697e5c9317743dc078f67693f"' , 'content-type' : 'application/json' } #HTTP 头部是大小写不敏感的,可以使用任意大写形式来访问这些响应头字段 >>> r.headers[ 'Content-Type' ] 'application/json' >>> r.headers.get( 'content-type' ) 'application/json' |
Cookie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #如果某个响应中包含一些 cookie,你可以快速访问它们: >>> url = 'http://example.com/some/cookie/setting/url' >>> r = requests.get(url) >>> r.cookies[ 'example_cookie_name' ] 'example_cookie_value' #要想发送你的cookies到服务器,可以使用 cookies 参数: >>> url = 'http://httpbin.org/cookies' >>> cookies = dict (cookies_are = 'working' ) >>> r = requests.get(url, cookies = cookies) >>> r.text '{"cookies": {"cookies_are": "working"}}' |
重定向和请求历史
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #可以使用响应对象的 history 方法来追踪重定向。 >>> r = requests.get( 'http://github.com' ) >>> r.url 'https://github.com/' >>> r.status_code 200 >>> r.history [<Response [ 301 ]>] #可以通过 allow_redirects 参数禁用重定向处理: >>> r = requests.get( 'http://github.com' , allow_redirects = False ) >>> r.status_code 301 >>> r.history [] |
超时
1 2 3 4 5 6 | #你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应: >>> requests.get( 'http://github.com' , timeout = 0.001 ) Traceback (most recent call last): File "<stdin>" , line 1 , in <module> requests.exceptions.Timeout: HTTPConnectionPool(host = 'github.com' , port = 80 ): Request timed out. (timeout = 0.001 ) |
初学linux,每学到一点东西就写一点,如有不对的地方,恳请包涵!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能