安装

  1. pip3 install requests

使用

发送请求

  1. import requests
  2.  
  3. r = requests.get('http://www.baidu.com')

还可以如下方式发送不同类型请求:

  1. r = requests.post('http://httpbin.org/post', data = {'key':'value'})
  2. r = requests.put('http://httpbin.org/put', data = {'key':'value'})
  3. r = requests.delete('http://httpbin.org/delete')
  4. r = requests.head('http://httpbin.org/get')
  5. r = requests.options('http://httpbin.org/get')

传递URL参数

  1. import requests
  2.  
  3. # 传递字典
  4. payload = {'key1': 'value1', 'key2': 'value2'}
  5. r = requests.get("http://httpbin.org/get", params=payload)
  6. print(r.url) # http://httpbin.org/get?key1=value1&key2=value2
  7.  
  8. # 传递字典套列表
  9. payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
  10. r = requests.get('http://httpbin.org/get', params=payload)
  11. print(r.url) # http://httpbin.org/get?key1=value1&key2=value2&key2=value3

响应文本内容

  1. import requests
  2.  
  3. r = requests.get('https://www.baidu.com')
  4. print(r.encoding) # ISO-8859-1 查看编码
  5. r.encoding = 'utf8' # 设置编码
  6. print(r.text)

二进制响应内容

  1. import requests
  2.  
  3. r = requests.get('https://assets.readthedocs.org/sustainability/jetbrains/pycharm3-fs8.png')
  4. file_name = r.url.rsplit('/', maxsplit=1)[1]
  5. with open(file_name, 'wb') as img_file:
  6. img_file.write(r.content)

JSON响应内容

  1. import requests
  2.  
  3. # 如果响应内容是 JSON 格式,就可以直接通过r.json()将 json 数据转换为字典
  4. r = requests.get('https://api.github.com/events')
  5. print(r.json())

定制请求头

  1. import requests
  2.  
  3. url = 'https://api.github.com/some/endpoint'
  4. headers = {'user-agent': 'my-app/0.0.1'}
  5.  
  6. r = requests.get(url, headers=headers)

复杂POST请求

  1. import requests
  2.  
  3. # 传递字典
  4. payload = {'key1': 'value1', 'key2': 'value2'}
  5. r = requests.post("http://httpbin.org/post", data=payload)
  6.  
  7. '''
  8. {
  9. "key2": "value2",
  10. "key1": "value1"
  11. }
  12. '''
  13. # 传递元组
  14. payload = (('key1', 'value1'), ('key1', 'value2'))
  15. r = requests.post('http://httpbin.org/post', data=payload)
  16. '''
  17. {
  18. "key1": [
  19. "value1",
  20. "value2"
  21. ]
  22. }
  23. '''
  24.  
  25. # 传递 JSON
  26. import json
  27.  
  28. url = 'http://127.0.0.1:5000/'
  29. payload = {'some': 'data'}
  30. r = requests.post(url, data=json.dumps(payload))
  31. # 此处除了可以自行对 dict 进行编码,你还可以使用 json 参数直接传递,然后它就会被自动编码
  32. r = requests.post(url, json=payload)

POST一个多部分编码(Multipart-Encoded)的文件

  1. import requests
  2.  
  3. # 上传文件
  4. url = 'http://httpbin.org/post'
  5. files = {'file': open('report.xls', 'rb')}
  6. r = requests.post(url, files=files)
  7.  
  8. # 显式地设置文件名,文件类型和请求头
  9. url = 'http://httpbin.org/post'
  10. files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': ''})}
  11. r = requests.post(url, files=files)
  12.  
  13. # 发送作为文件来接收的字符串
  14. url = 'http://httpbin.org/post'
  15. files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
  16. r = requests.post(url, files=files)

响应状态码

  1. import requests
  2.  
  3. r = requests.get('http://www.baidu.com')
  4. # 为方便引用,Requests 还附带了一个内置的状态码查询对象:
  5. print(r.status_code == requests.codes.ok)
  6.  
  7. # 如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常
  8. bad_r = requests.get('http://httpbin.org/status/500')
  9. print(bad_r.status_code) #
  10. bad_r.raise_for_status() # requests.exceptions.HTTPError: 500 Server Error

响应头

  1. import requests
  2.  
  3. r = requests.get('http://www.baidu.com')
  4. # 以查看以一个 Python 字典形式展示的服务器响应头:
  5. print(r.headers)
  6. '''
  7. {
  8. 'Server': 'bfe/1.0.8.18',
  9. 'Date': 'Tue, 25 Dec 2018 06:41:43 GMT',
  10. 'Content-Type': 'text/html',
  11. 'Last-Modified': 'Mon, 23 Jan 2017 13:28:11 GMT',
  12. 'Transfer-Encoding': 'chunked',
  13. 'Connection': 'Keep-Alive',
  14. 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform',
  15. 'Pragma': 'no-cache',
  16. 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/',
  17. 'Content-Encoding': 'gzip'
  18. }
  19. '''
  20. # HTTP 头部是大小写不敏感的。因此,我们可以使用任意大小写形式来访问这些响应头字段
  21. print(r.headers['Content-Type']) # text/html
  22. print(r.headers.get('content-type')) # text/html

Cookie

  1. import requests
  2.  
  3. # 如果某个响应中包含一些 cookie,你可以快速访问它们
  4. url = 'http://example.com/some/cookie/setting/url'
  5. r = requests.get(url)
  6. print(r.cookies['example_cookie_name'])
  7.  
  8. # 要想发送你的cookies到服务器,可以使用 cookies 参数
  9. url = 'http://httpbin.org/cookies'
  10. cookies = dict(cookies_are='working')
  11. r = requests.get(url, cookies=cookies)
  12.  
  13. # Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中
  14. jar = requests.cookies.RequestsCookieJar()
  15. jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
  16. jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
  17. url = 'http://httpbin.org/cookies'
  18. r = requests.get(url, cookies=jar)

重定向与请求历史

  1. import requests
  2.  
  3. # 默认情况下,除了 HEAD, Requests 会自动处理所有重定向。
  4. # 可以使用响应对象的 history 方法来追踪重定向。
  5. # Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。
  6. # 例如,Github 将所有的 HTTP 请求重定向到 HTTPS:
  7. r = requests.get('http://github.com')
  8. print(r.url) # https://github.com/
  9. print(r.history[0].url) # http://github.com/
  10.  
  11. # 如果你使用的是 GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理:
  12. r = requests.get('http://github.com', allow_redirects=False)
  13. print(r.url) # http://github.com/
  14. print(r.history) # []
  15.  
  16. # 如果你使用了 HEAD,你也可以启用重定向:
  17. r = requests.head('http://github.com', allow_redirects=True)

超时

  1. import requests
  2.  
  3. # 可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应:
  4. requests.get('http://github.com', timeout=0.001)
  5. '''
  6. Traceback (most recent call last):
  7. File "<stdin>", line 1, in <module>
  8. requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
  9. '''

错误与异常

遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。

如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有 Requests 显式抛出的异常都继承自 requests.exceptions.RequestException 。

更多

参考:http://docs.python-requests.org/zh_CN/latest/index.html

示例

requests和bs4爬取汽车之家文章和图片

  1. from gevent import monkey
  2.  
  3. monkey.patch_all()
  4. import gevent
  5. import requests
  6. import bs4
  7.  
  8. def save_detail(title, url_txt):
  9. article_detail_text = requests.get(url_txt).text
  10. detail_soup = bs4.BeautifulSoup(article_detail_text, features="html.parser")
  11. div_content = detail_soup.find(name='div', id='articleContent')
  12. p_img_list = div_content.find_all(name='p', attrs={'align': 'center'})
  13. for p_img in p_img_list:
  14. if p_img.find(name='img') != None and p_img.find(name='img').attrs != None:
  15. src = 'https:' + p_img.find(name='img').attrs.get('src')
  16. filename = src.rsplit('/', maxsplit=1)[1]
  17. img_resp = requests.get(src)
  18. with open('images/%s' % filename, 'wb') as f:
  19. f.write(img_resp.content)
  20. line_arr = []
  21. if (div_content != None):
  22. print(div_content.text)
  23. for line in div_content.find_all(name='p', align=False, recursive=False):
  24. line_arr.append(line.text)
  25. content = '\r\n'.join(line_arr)
  26. f = open('auto_home_articles/%s.txt' % title.replace('/', ' '), 'w+', encoding="utf-8")
  27. f.write(content)
  28. f.close()
  29.  
  30. def get_list_url():
  31. response = requests.get('https://www.autohome.com.cn/news/')
  32. response.encoding = 'gbk'
  33. list_soup = bs4.BeautifulSoup(response.text, features="html.parser")
  34. # 获取最大页数
  35. ul_page = list_soup.find(name='div', id='channelPage', class_='page')
  36. max_page_num = int(ul_page.find(class_='page-item-next').find_previous(name='a').text)
  37.  
  38. list_url_template = 'https://www.autohome.com.cn/news/%s/#liststart'
  39. return [list_url_template % i for i in range(1, max_page_num + 1)]
  40.  
  41. def start_save(list_url):
  42. list_page_resp = requests.get(list_url)
  43. list_page_resp.encoding = 'gbk'
  44. list_page_soup = bs4.BeautifulSoup(list_page_resp.text, features="html.parser")
  45. div = list_page_soup.find(name='div', id='auto-channel-lazyload-article')
  46. article_ul = div.find_all(name='ul', attrs={'class': 'article'})
  47. detail_url_list = []
  48. for article_list in article_ul:
  49. article_group = article_list.find_all(name='a')
  50. for article_item in article_group:
  51. title = article_item.find(name='h3').text
  52. url = article_item.attrs.get('href').replace('//', 'http://')
  53. detail_url_list.append((title, url,))
  54. gevent.joinall([gevent.spawn(save_detail, detail_url[0], detail_url[1]) for detail_url in detail_url_list])
  55.  
  56. [start_save(list_url) for list_url in iter(get_list_url())]

python之requests模块快速上手的更多相关文章

  1. Python爬虫---requests库快速上手

    一.requests库简介 requests是Python的一个HTTP相关的库 requests安装: pip install requests 二.GET请求 import requests # ...

  2. Python爬虫之使用Fiddler+Postman+Python的requests模块爬取各国国旗

    介绍   本篇博客将会介绍一个Python爬虫,用来爬取各个国家的国旗,主要的目标是为了展示如何在Python的requests模块中使用POST方法来爬取网页内容.   为了知道POST方法所需要传 ...

  3. Python之requests模块-hook

    requests提供了hook机制,让我们能够在请求得到响应之后去做一些自定义的操作,比如打印某些信息.修改响应内容等.具体用法见下面的例子: import requests # 钩子函数1 def ...

  4. Python之requests模块-cookie

    cookie并不陌生,与session一样,能够让http请求前后保持状态.与session不同之处,在于cookie数据仅保存于客户端.requests也提供了相应到方法去处理cookie. 在py ...

  5. Python之requests模块-session

    http协议本身是无状态的,为了让请求之间保持状态,有了session和cookie机制.requests也提供了相应的方法去操纵它们. requests中的session对象能够让我们跨http请求 ...

  6. Python之requests模块-request api

    requests所有功能都能通过"requests/api.py"中的方法访问.它们分别是: requests.request(method, url, **kwargs) req ...

  7. Python使用requests模块访问HTTPS网站报错`certificate verify failed`

    使用requests模块访问HTTPS网站报错: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Nam ...

  8. 使用Python的requests模块编写请求脚本

    requests模块可用来编写请求脚本. 比如,使用requests的post函数可以模拟post请求: resp = requests.post(url, data = content) url即为 ...

  9. python基础-requests模块、异常处理、Django部署、内置函数、网络编程

     网络编程 urllib的request模块可以非常方便地抓取URL内容,也就是发送一个GET请求到指定的页面,然后返回HTTP的响应. 校验返回值,进行接口测试: 编码:把一个Python对象编码转 ...

随机推荐

  1. 设置GRUB密码以防止单用户模式下root密码被恶意更改

    在使用LInux系统的时候可能会发生忘记root密码的情况,通常管理员会进入单用户模式下进行重置root密码.那么问题来了,既然管理员可以进入单用户模式,如果恶意用户可以接触的到计算机的话毫无疑问也是 ...

  2. [20180312]进程管理其中的SQL Server进程占用内存远远大于SQL server内部统计出来的内存

    sql server 统计出来的内存,不管是这个,还是dbcc memorystatus,和进程管理器中内存差距很大,差不多有70G的差异. 具体原因不止,可能是内存泄漏,目前只能通过重启服务解决   ...

  3. CobaltStrike3.12/13 破解

    更新3.13破解版 链接: https://pan.baidu.com/s/14e0tpVPzUhiAhYU2_jvBag 提取码: d9uf MacOS客户端: 链接: https://pan.ba ...

  4. C++ 函数模板的返回类型如何确定?

    函数模板 #include <iostream> // 多个参数的函数木板 template<typename T1, typename T2> T2 max(T1 a, T2 ...

  5. windows下IDEA的terminal配置bash命令

    使用git-bash.exe会单独打开一个窗口,而我们希望是在终端内置的命令行.这里我使用bash.exe 在IDEA中,打开settings,设置相应的bash路径 settings–>Too ...

  6. 东南亚 SAP 实施 马来西亚税收在SAP的设计和实现

    马来西亚属于中等收入国家,现行税种主要有: 公司所得税.个人所得税.不动产利得税.石油所得税.销售税.合同税.暴利税.服务税和关税等. (一)主要税种1.公司所得税 ⑴ 纳税人 公司所得税的纳税人分为 ...

  7. php异步执行其他程序

    这里的“其他程序”,可能是linux命令,可能是其他的php文件. 网上说法有四种.分别为: 1.通过加载页面的时候通过ajax技术异步请求服务器 2.通过popen()函数 3.通过curl扩展 4 ...

  8. [2]朝花夕拾-JAVA注解、PHP注解?

    一.Java注解概述 注解,也被称为元数据,为我们在代码中添加信息提供了一种形式化的方法,是我们可以在稍后某个时刻非常方便地使用这些数据. 注解在一定程度上是把元数据与源代码文件结合在一起,而不是保存 ...

  9. 7、 jade 、 ejs、express集成模板

    jade/ejs 模板引擎 http://jade-lang.com/ http://www.nooong.com/docs/jade_chinese.htm SSR 服务器端渲染 服务器生成html ...

  10. 验证IP地址的有效性

    实力说明 IP地址是网络上每台计算机的标识,在浏览器中输入的网址也是要经过DNS服务器转换为IP地址才能找到服务器. 关键技术 正则表达式