developer tip

인증 된 (로그인 된) 사용자 세션으로 Scrapy 사용

copycodes 2020. 12. 31. 22:15
반응형

인증 된 (로그인 된) 사용자 세션으로 Scrapy 사용


Scrapy 문서 에는 Scrapy 에서 인증 된 세션을 사용하는 방법을 설명하는 다음 예제가 있습니다.

class LoginSpider(BaseSpider):
    name = 'example.com'
    start_urls = ['http://www.example.com/users/login.php']

    def parse(self, response):
        return [FormRequest.from_response(response,
                    formdata={'username': 'john', 'password': 'secret'},
                    callback=self.after_login)]

    def after_login(self, response):
        # check login succeed before going on
        if "authentication failed" in response.body:
            self.log("Login failed", level=log.ERROR)
            return

        # continue scraping with authenticated session...

나는 그 일이 있고 괜찮습니다. 그러나 내 질문은 : continue scraping with authenticated session그들이 마지막 줄의 주석에서 말하는 것처럼 무엇을해야 합니까?


위의 코드 FormRequest에서 인증에 사용 after_login되는는 콜백으로 설정된 함수를 가지고 있습니다. 이것은 after_login함수가 호출되고 로그인 시도가 응답으로받은 페이지를 전달 함을 의미합니다 .

그런 다음 페이지에서 특정 문자열 (이 경우)을 검색하여 성공적으로 로그인되었는지 확인합니다 "authentication failed". 그것을 찾으면 거미가 끝납니다.

이제 스파이더가이 정도까지 도달하면 성공적으로 인증되었음을 알고 새 요청 생성 및 / 또는 데이터 스크랩을 시작할 수 있습니다. 따라서이 경우 :

from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request

# ...

def after_login(self, response):
    # check login succeed before going on
    if "authentication failed" in response.body:
        self.log("Login failed", level=log.ERROR)
        return
    # We've successfully authenticated, let's have some fun!
    else:
        return Request(url="http://www.example.com/tastypage/",
               callback=self.parse_tastypage)

def parse_tastypage(self, response):
    hxs = HtmlXPathSelector(response)
    yum = hxs.select('//img')

    # etc.

여기 를 보면 긁기 전에 인증하는 스파이더의 예가 있습니다.

이 경우 parse함수 (모든 요청의 기본 콜백) 에서 작업을 처리합니다 .

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    if hxs.select("//form[@id='UsernameLoginForm_LoginForm']"):
        return self.login(response)
    else:
        return self.get_section_links(response)

따라서 요청이있을 때마다 로그인 양식이 있는지 응답을 확인합니다. 거기에 있다면 로그인이 필요하다는 것을 알기 때문에 관련 함수를 호출하고, 존재하지 않으면 응답에서 데이터를 스크랩하는 함수를 호출합니다.

이것이 명확하기를 바랍니다. 다른 질문이 있으면 언제든지 물어보세요!


편집하다:

좋습니다. 단일 요청을 생성하고 스크래핑하는 것 이상을 원합니다. 링크를 따르고 싶습니다.

To do that, all you need to do is scrape the relevant links from the page, and spawn requests using those URLs. For example:

def parse_page(self, response):
    """ Scrape useful stuff from page, and spawn new requests

    """
    hxs = HtmlXPathSelector(response)
    images = hxs.select('//img')
    # .. do something with them
    links = hxs.select('//a/@href')

    # Yield a new request for each link we found
    for link in links:
        yield Request(url=link, callback=self.parse_page)

As you can see, it spawns a new request for every URL on the page, and each one of those requests will call this same function with their response, so we have some recursive scraping going on.

What I've written above is just an example. If you want to "crawl" pages, you should look into CrawlSpider rather than doing things manually.

ReferenceURL : https://stackoverflow.com/questions/5850755/using-scrapy-with-authenticated-logged-in-user-session

반응형