본문 바로가기
파이썬

파이썬 동적 페이지를위한 스크래피가있는 셀레늄

by º기록 2021. 1. 10.
반응형

스크래피를 사용하여 웹 페이지에서 제품 정보를 긁어 내려고합니다. 스크랩 할 웹 페이지는 다음과 같습니다.

next-button-ajax-call을 복제하려고했지만 작동하지 않아서 셀레늄을 사용해 보았습니다. 셀레늄의 웹 드라이버를 별도의 스크립트로 실행할 수 있지만 스크래피와 통합하는 방법을 모르겠습니다. 긁힌 거미에 셀레늄 부분을 어디에 넣을까요?

내 거미는 다음과 같이 꽤 표준입니다.

class ProductSpider(CrawlSpider):
    name = "product_spider"
    allowed_domains = ['example.com']
    start_urls = ['http://example.com/shanghai']
    rules = [
        Rule(SgmlLinkExtractor(restrict_xpaths='//div[@id="productList"]//dl[@class="t2"]//dt'), callback='parse_product'),
        ]

    def parse_product(self, response):
        self.log("parsing product %s" %response.url, level=INFO)
        hxs = HtmlXPathSelector(response)
        # actual data follows

어떤 아이디어라도 감사합니다. 감사합니다!

 

해결 방법

 

실제로 사이트를 스크래핑해야하는 방법과 얻고 자하는 데이터가 무엇인지에 따라 다릅니다.

다음은 Scrapy + Selenium 을 사용하여 eBay에서 페이지 매김을 수행하는 방법의 예입니다.

import scrapy
from selenium import webdriver

class ProductSpider(scrapy.Spider):
    name = "product_spider"
    allowed_domains = ['ebay.com']
    start_urls = ['http://www.ebay.com/sch/i.html?_odkw=books&_osacat=0&_trksid=p2045573.m570.l1313.TR0.TRC0.Xpython&_nkw=python&_sacat=0&_from=R40']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_xpath('//td[@class="pagn-next"]/a')

            try:
                next.click()

                # get the data and write it to scrapy items
            except:
                break

        self.driver.close()

다음은 "셀레늄 거미"의 몇 가지 예입니다.







 

참조 페이지 https://stackoverflow.com/questions/17975471

 

 

반응형

댓글