【问题标题】:scrapy selenium pagination刮痧硒分页
【发布时间】:2016-01-25 04:43:30
【问题描述】:

我正在尝试抓取tripadvisor's website。我使用了两种方法,第一种是使用 CrawlSpiders 和 Rules。对结果不太满意,我现在尝试使用 Selenium 浏览每个链接。唯一的问题是分页问题。我希望 selenium 浏览器打开网页并浏览 starturl 中的每个链接,然后单击底部的下一页。到目前为止,我编写的代码只是为了提取所需的内容:

    self.driver.get(response.url)
    div_val = self.driver.find_elements_by_xpath('//div[@class="tab_contents"]')
    for link in div_val:
        l = link.find_element_by_tag_name('a').get_attribute('href')
        if re.match(r'http:\/\/www\.tripadvisor\.com\/Hotels\-g[\d]*\-Dominican\_Republic\-Hotels\.html',l):
            link.click()
            time.sleep(5)

                try:
                    hotel_links = self.driver.find_elements_by_xpath('//div[@class="listing_title"]')
                    for hotel_link in hotel_links:
                        lnk = hotel_link.find_element_by_class_name('property_title').get_attribute('href')

                except NoSuchElementException:
                    print 'elemenotfound

我现在被硒分页所困扰。

【问题讨论】:

  • 您可以自动单击下一步按钮并在请求之间暂停。我认为这对您很有效。如果我是正确的,您是否要输入列表等每个链接并提取数据,然后完成您要单击下一步按钮的所有页面?

标签: python selenium pagination web-scraping


【解决方案1】:

我认为 CrawlSpider 和 Selenium 的组合对你有用 -

for click in range(0,15):#clicking on next button for pagination
    button = self.driver.xpath("/html/body/div[3]/div[7]/div[2]/div[7]/div[2]/div[1]/div[3]/div[2]/div/div/div[41]/div[2]/div/a")

    button.click()

    time.sleep(10)

    for i in range(0,10):#range depends upon number of listings you can change it# for entering into the individual url using response
            item['url'] = response.xpath('a[contains(@class,"property_title ")]/@href').extract()[i]
            if item['url']:
                                                    if 'http://' not in item['url']:
                                                        item['url'] = urljoin(response.url, item['url'])
                                                    yield scrapy.Request(item['url'],
                                                                        meta={'item': item},
                                                                        callback=self.anchor_page)


                def anchor_page(self, response):

                    old_item = response.request.meta['item']

                    data you want to scrape
                    yield old_item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    相关资源
    最近更新 更多