>  기사  >  백엔드 개발  >  Python 크롤러 Scrapy는 프록시 구성을 사용합니다.

Python 크롤러 Scrapy는 프록시 구성을 사용합니다.

高洛峰
高洛峰원래의
2016-10-17 13:56:572224검색

웹사이트 콘텐츠를 크롤링할 때 가장 흔히 발생하는 문제는 웹사이트에 IP 제한이 있고 크롤링 방지 기능이 있다는 것입니다. 가장 좋은 방법은 IP 캡처를 순환(프록시 추가)하는 것입니다.

에 대해 이야기해 보겠습니다. Scrapy가 크롤링을 위해 프록시를 구성하는 방법

1. Scrapy 프로젝트

# Importing base64 library because we'll need it ONLY in case if the proxy we are going to use requires authentication
import base64 
# Start your middleware class
class ProxyMiddleware(object):
    # overwrite process request
    def process_request(self, request, spider):
        # Set the location of the proxy
        request.meta['proxy'] = "http://YOUR_PROXY_IP:PORT"
  
        # Use the following lines if your proxy requires authentication
        proxy_user_pass = "USERNAME:PASSWORD"
        # setup basic authentication for the proxy
        encoded_user_pass = base64.encodestring(proxy_user_pass)
        request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass

에서 새 "middlewares.py"를 만듭니다. 프로젝트 구성 파일(./pythontab/settings.py)

DOWNLOADER_MIDDLEWARES = {
    'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,
    'pythontab.middlewares.ProxyMiddleware': 100,
}


을 추가합니다.
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.