爬虫requests基本用法二

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/86347255

一 抓取网页

1 代码

import requests
import re
# headers信息,其中包含了User-Agent字段信息,也就是浏览器标识信息。如果不加这个,知乎会禁止抓取。
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
r = requests.get("https://www.zhihu.com/explore", headers=headers)
# 接下来我们用到了最基础的正则表达式来匹配出所有的问题内容。
pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)
titles = re.findall(pattern, r.text)
print(titles)

2 结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_2_1.py
['\n南半球有没有传统天文学?\n', '\n二十世纪初的维也纳为什么聚集众多伟大人物?\n', '\n有哪些适合新手起步的家常菜?\n', '\n膨胀中的宇宙依然符合能量守恒定律吗?\n', '\n大学本科经济学/数学问题:无差异曲线为何不用空间直角坐标系解释?\n', '\n有什么书籍推荐给医学生看?\n', '\n有哪些华语演员擅长用眼神来演戏?\n', '\n有哪些对大学生有意义的手机 App?\n', '\n柾国最近的活跃是发生了什么?\n', '\n什么时候你真的很心疼一只狗?\n']

二 抓取二进制数据

1 代码

# 图片、音频、视频这些文件本质上都是由二进制码组成的,由于有特定的保存格式和对应的解析方式,
# 我们才可以看到这些形形色色的多媒体。所以,想要抓取它们,就要拿到它们的二进制码。
import requests

r = requests.get("https://github.com/favicon.ico")
# Response对象的两个属性
print(r.text)
print(r.content)
# 它的第一个参数是文件名称,第二个参数代表以二进制写的形式打开,可以向文件里写入二进制数据。
with open('favicon.ico', 'wb') as f:
    f.write(r.content)

2 运行结果

3 说明

前者出现了乱码,后者结果前带有一个b,这代表是bytes类型的数据。由于图片是二进制数据,所以前者在打印时转化为str类型,也就是图片直接转化为字符串,这理所当然会出现乱码。

运行结束之后,可以发现在文件夹中出现了名为favicon.ico的图标

三 POST请求

1 代码

import requests

data = {'name': 'germey', 'age': '22'}
# 这里还是请求http://httpbin.org/post,
# 该网站可以判断如果请求是POST方式,就把相关请求信息返回。
r = requests.post("http://httpbin.org/post", data=data)
print(r.text)

2 运行结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_2_1.py
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "age": "22",
    "name": "germey"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "18",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.21.0"
  },
  "json": null,
  "origin": "106.36.218.77",
  "url": "http://httpbin.org/post"
}

3 说明

成功获得了返回结果,其中form部分就是提交的数据,这就证明POST请求成功发送了。

四 响应

1 代码

import requests

r = requests.get('http://www.jianshu.com')
# 状态码
print(type(r.status_code), r.status_code)
# headers属性得到响应头
print(type(r.headers), r.headers)
# cookies属性得到Cookies
print(type(r.cookies), r.cookies)
# 输出url属性得到URL
print(type(r.url), r.url)
# history属性得到请求历史。
print(type(r.history), r.history)

2 运行结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_2_1.py
<class 'int'> 403
<class 'requests.structures.CaseInsensitiveDict'> {'Date': 'Sat, 12 Jan 2019 01:28:48 GMT', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Server': 'Tengine', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Content-Encoding': 'gzip', 'X-Via': '1.1 PSzjwzdx11at80:10 (Cdn Cache Server V2.0), 1.1 PSsxwndx4au44:4 (Cdn Cache Server V2.0)'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
<class 'str'> https://www.jianshu.com/
<class 'list'> [<Response [301]>]

3 说明

可以看到,headers和cookies这两个属性得到的结果分别是CaseInsensitiveDict和RequestsCookieJar类型。

五 内置状态码

1 代码

import requests

r = requests.get('http://www.jianshu.com')
exit() if not r.status_code == requests.codes.ok else print('Request Successfully')

2 说明

返回码和相应的查询条件
# 信息性状态码
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
# 成功状态码
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# 重定向状态码
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
      'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# 客户端错误状态码
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# 服务端错误状态码
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication')

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/86347255
今日推荐