>  기사  >  백엔드 개발  >  Python 크롤러 요청 라이브러리를 사용하는 방법

Python 크롤러 요청 라이브러리를 사용하는 방법

王林
王林앞으로
2023-05-16 11:46:051012검색

1. 요청 라이브러리 설치

학습 과정에서는 Python 언어를 사용하기 때문에 Python 3.8을 미리 설치해야 합니다. python --version 명령을 실행하면 설치된 Python 버전을 확인할 수 있습니다. Python 3. 버전 X 이상을 설치하는 것이 좋습니다.

Python 크롤러 요청 라이브러리를 사용하는 방법

Python을 설치한 후 다음 명령을 통해 요청 라이브러리를 직접 설치할 수 있습니다.

pip install requests

Ps: Alibaba, Douban 등 국내 pip 소스로 빠르게 전환할 수 있습니다.
기능을 시연하기 위해 nginx를 사용하여 간단한 웹사이트를 시뮬레이션했습니다.
다운로드 후 루트 디렉터리에서 nginx.exe 프로그램을 직접 실행하세요(참고: Windows 환경의 경우).
이때 로컬 컴퓨터가 http://127.0.0.1에 접속하면 nginx의 기본 페이지로 들어갑니다.

Python 크롤러 요청 라이브러리를 사용하는 방법

2. 웹 페이지 가져오기

다음으로 요청을 사용하여 요청을 시뮬레이션하고 페이지 소스 코드를 가져옵니다.

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

실행 후 얻은 결과는 다음과 같습니다.

nbsp;html><title>Welcome to nginx!</title><style>    body {        width: 35em;        margin: 0 auto;        font-family: Tahoma, Verdana, Arial, sans-serif;    }</style><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>nginx.org</a>.<br>Commercial support is available at<a>nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>

3. 요청에 대하여

일반적인 요청이 많이 있습니다. 예를 들어 위의 예에서는 이러한 일반적인 요청 방법에 대해 자세히 소개합니다. .

4. GET 요청

4.1. 요청 시작

동일한 방법을 사용하여 GET 요청을 시작합니다.

import requests  r = requests.get('http://httpbin.org/get')  print(r.text)

반환 결과는 다음과 같습니다.

{"args": {}, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.23.0", "X-Amzn-Trace-Id": "Root=1-5f846520-19f215aa46213a2b4241c18a"  }, "origin": "xxxx", "url": "http://httpbin.org/get"}

결과를 반환하면 반환 결과를 확인하세요. 포함된 정보는 헤더, URL, IP 등입니다.

4.2. 매개변수 추가

일반적으로 우리가 방문하는 URL에는 ID는 100, 이름은 YOOAO와 같은 일부 매개변수가 포함됩니다. 정상적인 접속을 위해서는 다음과 같이 접속 URL을 작성하겠습니다.

http://httpbin.org/get?id=100&name=YOOAO

분명 매우 불편하고, 매개변수가 많으면 오류가 발생하기 쉽습니다. 이때 params 매개변수를 통해 입력 내용을 최적화할 수 있습니다.

import requests  data = {      'id': '100',      'name': 'YOOAO'}  r = requests.get('http://httpbin.org/get', params=data)  print(r.text)

다음과 같은 코드를 실행하여 반환된 결과입니다.

{"args": {"id": "100", "name": "YOOAO"  }, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.23.0", "X-Amzn-Trace-Id": "Root=1-5f84658a-1cd0437b4cf34835410d7161"  }, "origin": "xxx.xxxx.xxx.xxx", "url": "http://httpbin.org/get?id=100&name=YOOAO"}

결과를 반환하면 사전을 통해 전달된 매개변수가 자동으로 완전한 URL로 구성되어 수동으로 완성할 필요가 없음을 알 수 있습니다. 우리 스스로 건설.

4.3.반환 결과 처리

반환 결과는 json 형식이므로 json을 호출하여 구문 분석하는 방법을 사용할 수 있습니다. 반환된 콘텐츠가 json 형식이 아닌 경우 이 호출은 오류를 보고합니다.

import requests  
r = requests.get('http://httpbin.org/get')  print(type(r.text))   print(type(r.json()))

반환 결과:

<class><class></class></class>

4.4. 콘텐츠 캡처

여기에서는 간단한 정규식을 사용하여 nginx 샘플 페이지의 모든 태그의 콘텐츠를 캡처합니다. 결과 가져오기:

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

여기에서 간단한 페이지 획득 및 콘텐츠 크롤링이 완료되었습니다.

4.5, 데이터 파일 다운로드

페이지 정보를 얻으려는 경우 위의 예는 모든 페이지 정보를 반환합니다. 이미지, 오디오 및 비디오의 경우 파일을 저장하려면 페이지의 바이너리 데이터를 캡처하는 방법을 배워야 합니다. open 메소드를 사용하면 이미지와 같은 바이너리 파일의 다운로드를 완료할 수 있습니다. 예시 코드:

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

open 메소드에서 첫 번째 매개변수는 파일 이름이고 두 번째 매개변수는 바이너리 형식으로 열기를 의미하며 다음과 같은 작업을 수행할 수 있습니다. 파일에 쓰기 바이너리 데이터를 입력합니다.

작업이 완료되면 다운로드한 사진은 실행 중인 파일과 동일한 폴더에 저장됩니다. 동일한 원리를 사용하여 비디오 및 오디오 파일을 처리할 수 있습니다.

4.6. 헤더 추가

위의 예에서는 헤더를 추가하지 않고 직접 요청을 시작했습니다. 일부 웹사이트에서는 요청 헤더가 없기 때문에 액세스 예외가 발생합니다. 여기서는 헤더 콘텐츠를 수동으로 추가하고 Uer 추가를 시뮬레이션할 수 있습니다. -헤더 내 에이전트 콘텐츠 코드:

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

실행 결과:

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('http://httpbin.org/get', headers=headers)print(r.text)

결과를 보면 User-Agent의 값이 변경된 것을 확인할 수 있습니다. 이전 것이 아닙니다: python-requests/2.23.0.

5. POST 요청

이제 GET 요청에 대해 배웠으니 또 다른 일반적인 요청 방법인 POST 요청에 대해 이야기해 보겠습니다.

使用 requests 实现 POST 请求的代码如下:

import requestsdata = {      'id': '100',      'name': 'YOOAO'}  
r = requests.post("http://httpbin.org/post", data=data)print(r.text)

结果如下

{"args": {}, "data": "", "files": {}, "form": {"id": "100", "name": "YOOAO"  }, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "17", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.23.0", "X-Amzn-Trace-Id": "Root=1-5ec8f4a0-affca27a05e320a84ca6535a"  }, "json": null, "origin": "xxxx", "url": "http://httpbin.org/post"}

从 form 中我们看到了自己提交的数据,可见我们的 POST 请求访问成功。

6、响应

访问URL时,有请求就会有响应,上面的示例使用 text 和 content 获取了响应的内容。除此以外,还有很多属性和方法可以用来获取其他信息,比如状态码、响应头、Cookies 等。

import requests
r = requests.get('http://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('http://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: ('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')

7、SSL 证书验证

现在很多网站都会验证证书,我们可以设置参数来忽略证书的验证。

import requests
response = requests.get('https://XXXXXXXX', verify=False)print(response.status_code)

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

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

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

8、设置超时

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

示例代码:

import requests# 设置超时时间为 10 秒r = requests.get('https://httpbin.org/get', timeout=10)print(r.status_code)

将连接时间和读取时间分开计算:

r = requests.get('https://httpbin.org/get', timeout=(3, 10))

不添加参数,默认不设置超时时间,等同于:

r = requests.get('https://httpbin.org/get', timeout=None)

9、身份认证

遇到一些网站需要输入用户名和密码,我们可以通过 auth 参数进行设置。

import requests  from requests.auth import HTTPBasicAuth  # 用户名为 admin ,密码为 admin r = requests.get('https://xxxxxx/', auth=HTTPBasicAuth('admin', 'admin'))  print(r.status_code)

简化写法:

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

10、设置代理

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

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

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

http://user:password@host/ 语法:

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

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

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

위 내용은 Python 크롤러 요청 라이브러리를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제