如何用Python的Requests库进行长尾词爬虫?

2026-04-13 09:231阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计2089个文字,预计阅读时间需要9分钟。

如何用Python的Requests库进行长尾词爬虫?

安装requests库是因为学习过程中使用的Python语言,需要先安装Python。我安装的是Python 3.8,可以通过命令`python --version`查看已安装的Python版本。建议安装Python 3.X及以上版本。

1、安装 requests 库

因为学习过程使用的是 Python 语言,需要提前安装 Python ,我安装的是 Python 3.8,可以通过命令 python --version 查看自己安装的 Python 版本,建议安装 Python 3.X 以上的版本。

安装好 Python 以后可以 直接通过以下命令安装 requests 库。

pip install requests

Ps:可以切换到国内的pip源,例如阿里、豆瓣,速度快
为了演示功能,我这里使用nginx模拟了一个简单网站。
下载好了以后,直接运行根目录下的 nginx.exe 程序就可以了(备注:windows环境下)。
这时本机访问 :127.0.0.1 ,会进入 nginx 的一个默认页面。

2、获取网页

下面我们开始用 requests 模拟一个请求,获取页面源代码。

import requestsr = requests.get('127.0.0.1')print(r.text)

执行以后得到的结果如下:

如何用Python的Requests库进行长尾词爬虫?

<!DOCTYPE html><html><head><title>Welcome to nginx!</title><style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; }</style></head><body><h2>Welcome to nginx!</h2><p>If you see this page, the nginx web server is successfully installed andworking. Further configuration is required.</p> <p>For online documentation and support please refer to<a href="nginx.org/">nginx.org</a>.<br/>Commercial support is available at<a href="nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p></body></html>

3、关于请求

常见的请求有很多种,比如上面的示例使用的就是 GET 请求,这里详细介绍一下这些常见的请求方法。

4、GET 请求

4.1、发起请求

我们使用相同的方法,发起一个 GET 请求:

import requests r = requests.get('127.0.0.1')pattern = re.compile('<a.*?>(.*?)</a>', re.S)a_content = re.findall(pattern, r.text)print(a_content)

抓取结果:

['nginx.org', 'nginx.com']

这里一次简单的页面获取和内容抓取就完成了,

4.5、数据文件下载

上面的示例,返回的都是页面信息,如果我们想获取网页上的图片、音频和视频文件,我们就需要学会抓取页面的二进制数据。我们可以使用 open 方法来完成图片等二进制文件的下载,示例代码:

import requests r = requests.get('tu.ossfiles.cn:9186/group3/M00/09/FB/rBpVfl8QFLOAYhhcAAC-pTdNj7g471.jpg')with open('image.jpg', 'wb') as f: f.write(r.content)print('下载完成')

open 方法中,它的第一个参数是文件名称,第二个参数代表以二进制的形式打开,可以向文件里写入二进制数据。

运行结束以后,会在运行文件的同级文件夹下保存下载下来的图片。运用同样原理,我们可以处理视频和音频文件。

4.6、添加headers

在上面的示例中,我们直接发起的请求,没有添加 headers ,某些网站为因为请求不携带请求头而造成访问异常,这里我们可以手动添加 headers 内容,模拟添加 headers 中的 Uer-Agent 内容代码:

import requests headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'}r = requests.get('127.0.0.1/')print(type(r.status_code), r.status_code)print(type(r.headers), r.headers)print(type(r.cookies), r.cookies)print(type(r.url), r.url)print(type(r.history), r.history)

关于状态码,requests 还提供了一个内置的状态码查询对象 requests.codes,用法示例如下:

import requestsr = requests.get('127.0.0.1/')exit() if not r.status_code == requests.codes.ok else print('Request Successfully')==========执行结果==========Request Successfully

这里通过比较返回码和内置的成功的返回码,来保证请求得到了正常响应,输出成功请求的消息,否则程序终止。

这里我们用 requests.codes.ok 得到的是成功的状态码 200。

这样的话,我们就不用再在程序里面写状态码对应的数字了,用字符串表示状态码会显得更加直观。

下面是响应码和查询条件对照信息:

# 信息性状态码 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: ('XXXXXXXX', verify=False)print(response.status_code)

或者制定本地证书作为客户端证书:

import requests response = requests.get('xxxxxx', cert=('/path/server.crt', '/path/server.key'))print(response.status_code)

注意:本地私有证书的 key 必须是解密状态,加密状态的 key 是不支持的。

8、设置超时

很多时候我们需要设置超时时间来控制访问的效率,遇到访问慢的链接直接跳过。

示例代码:

import requests# 设置超时时间为 10 秒r = requests.get('xxxxxx/', auth=HTTPBasicAuth('admin', 'admin')) print(r.status_code)

简化写法:

import requests r = requests.get('xxxxxx', auth=('admin', 'admin'))print(r.status_code)

10、设置代理

如果频繁的访问某个网站时,后期会被一些反爬程序识别,要求输入验证信息,或者其他信息,甚至IP被封无法再次访问,这时候,我们可以通过设置代理来避免这样的问题。

import requests proxies = { "10.10.1.10:3128", "10.10.1.10:1080",} requests.get("example.org", proxies=proxies)

若你的代理需要使用HTTP Basic Auth,可以使用

user:password@host/ 语法:

proxies = { "user:pass@10.10.1.10:3128/",}

要为某个特定的连接方式或者主机设置代理,使用 scheme://hostname 作为 key, 它会针对指定的主机和连接方式进行匹配。

proxies = {'10.20.1.128': '10.10.1.10:5323'}

本文共计2089个文字,预计阅读时间需要9分钟。

如何用Python的Requests库进行长尾词爬虫?

安装requests库是因为学习过程中使用的Python语言,需要先安装Python。我安装的是Python 3.8,可以通过命令`python --version`查看已安装的Python版本。建议安装Python 3.X及以上版本。

1、安装 requests 库

因为学习过程使用的是 Python 语言,需要提前安装 Python ,我安装的是 Python 3.8,可以通过命令 python --version 查看自己安装的 Python 版本,建议安装 Python 3.X 以上的版本。

安装好 Python 以后可以 直接通过以下命令安装 requests 库。

pip install requests

Ps:可以切换到国内的pip源,例如阿里、豆瓣,速度快
为了演示功能,我这里使用nginx模拟了一个简单网站。
下载好了以后,直接运行根目录下的 nginx.exe 程序就可以了(备注:windows环境下)。
这时本机访问 :127.0.0.1 ,会进入 nginx 的一个默认页面。

2、获取网页

下面我们开始用 requests 模拟一个请求,获取页面源代码。

import requestsr = requests.get('127.0.0.1')print(r.text)

执行以后得到的结果如下:

如何用Python的Requests库进行长尾词爬虫?

<!DOCTYPE html><html><head><title>Welcome to nginx!</title><style> body { width: 35em; margin: 0 auto; font-family: Tahoma, Verdana, Arial, sans-serif; }</style></head><body><h2>Welcome to nginx!</h2><p>If you see this page, the nginx web server is successfully installed andworking. Further configuration is required.</p> <p>For online documentation and support please refer to<a href="nginx.org/">nginx.org</a>.<br/>Commercial support is available at<a href="nginx.com/">nginx.com</a>.</p> <p><em>Thank you for using nginx.</em></p></body></html>

3、关于请求

常见的请求有很多种,比如上面的示例使用的就是 GET 请求,这里详细介绍一下这些常见的请求方法。

4、GET 请求

4.1、发起请求

我们使用相同的方法,发起一个 GET 请求:

import requests r = requests.get('127.0.0.1')pattern = re.compile('<a.*?>(.*?)</a>', re.S)a_content = re.findall(pattern, r.text)print(a_content)

抓取结果:

['nginx.org', 'nginx.com']

这里一次简单的页面获取和内容抓取就完成了,

4.5、数据文件下载

上面的示例,返回的都是页面信息,如果我们想获取网页上的图片、音频和视频文件,我们就需要学会抓取页面的二进制数据。我们可以使用 open 方法来完成图片等二进制文件的下载,示例代码:

import requests r = requests.get('tu.ossfiles.cn:9186/group3/M00/09/FB/rBpVfl8QFLOAYhhcAAC-pTdNj7g471.jpg')with open('image.jpg', 'wb') as f: f.write(r.content)print('下载完成')

open 方法中,它的第一个参数是文件名称,第二个参数代表以二进制的形式打开,可以向文件里写入二进制数据。

运行结束以后,会在运行文件的同级文件夹下保存下载下来的图片。运用同样原理,我们可以处理视频和音频文件。

4.6、添加headers

在上面的示例中,我们直接发起的请求,没有添加 headers ,某些网站为因为请求不携带请求头而造成访问异常,这里我们可以手动添加 headers 内容,模拟添加 headers 中的 Uer-Agent 内容代码:

import requests headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'}r = requests.get('127.0.0.1/')print(type(r.status_code), r.status_code)print(type(r.headers), r.headers)print(type(r.cookies), r.cookies)print(type(r.url), r.url)print(type(r.history), r.history)

关于状态码,requests 还提供了一个内置的状态码查询对象 requests.codes,用法示例如下:

import requestsr = requests.get('127.0.0.1/')exit() if not r.status_code == requests.codes.ok else print('Request Successfully')==========执行结果==========Request Successfully

这里通过比较返回码和内置的成功的返回码,来保证请求得到了正常响应,输出成功请求的消息,否则程序终止。

这里我们用 requests.codes.ok 得到的是成功的状态码 200。

这样的话,我们就不用再在程序里面写状态码对应的数字了,用字符串表示状态码会显得更加直观。

下面是响应码和查询条件对照信息:

# 信息性状态码 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: ('XXXXXXXX', verify=False)print(response.status_code)

或者制定本地证书作为客户端证书:

import requests response = requests.get('xxxxxx', cert=('/path/server.crt', '/path/server.key'))print(response.status_code)

注意:本地私有证书的 key 必须是解密状态,加密状态的 key 是不支持的。

8、设置超时

很多时候我们需要设置超时时间来控制访问的效率,遇到访问慢的链接直接跳过。

示例代码:

import requests# 设置超时时间为 10 秒r = requests.get('xxxxxx/', auth=HTTPBasicAuth('admin', 'admin')) print(r.status_code)

简化写法:

import requests r = requests.get('xxxxxx', auth=('admin', 'admin'))print(r.status_code)

10、设置代理

如果频繁的访问某个网站时,后期会被一些反爬程序识别,要求输入验证信息,或者其他信息,甚至IP被封无法再次访问,这时候,我们可以通过设置代理来避免这样的问题。

import requests proxies = { "10.10.1.10:3128", "10.10.1.10:1080",} requests.get("example.org", proxies=proxies)

若你的代理需要使用HTTP Basic Auth,可以使用

user:password@host/ 语法:

proxies = { "user:pass@10.10.1.10:3128/",}

要为某个特定的连接方式或者主机设置代理,使用 scheme://hostname 作为 key, 它会针对指定的主机和连接方式进行匹配。

proxies = {'10.20.1.128': '10.10.1.10:5323'}