Scrapy 和 Selenium:如何在循环中调用方法

Scrapy & Selenium: How to call a method in a loop

我已经在这里找到了类似的问题,但我的爬虫还没有 运行ning。

我正在尝试抓取从 txt.file 中提取的几个 URL。 这工作正常。但是,scrapy/selenium 为每个 URL 一个接一个地打开浏览器,但没有 运行 "crawltips" 功能。只有我的 txt.file 中的最后一个 URL 才会执行 def crawltips(self, response): 中的代码。

如何为 txt.file 中的每个 URL 调用 "crawltips" 函数?

class AlltipsSpider(Spider):
    name = 'allclasses'
    allowed_domains = ['dummy.com']



    def start_requests(self):

        self.driver = webdriver.Chrome('C:\webdrivers\chromedriver.exe')
        with open("urls.txt", "rt") as f:
            start_urls = [l.strip() for l in f.readlines()]

        for url in start_urls:
            self.driver.get(url)
            self.driver.find_element_by_id('currentTab').click()
            self.driver.find_element_by_xpath('//*[@id="_blog-menu"]/div[2]/div/div[2]/a[3]').click()
            yield Request(self.driver.current_url, callback=self.crawltips)


    def crawltips(self, response):


        sel = Selector(text=self.driver.page_source)
        allposts = sel.xpath('//*[@class="block media _feedPick feed-pick"]')
        for post in allposts:
            username = post.xpath('.//div[@class="col-sm-7 col-lg-6 no-padding"]/a/@title').extract()
            publish_date = post.xpath('.//*[@class="bet-age text-muted"]/text()').extract()


            yield{'Username': username,
                'Publish date': publish_date                
                }

据我了解,WebDriver 一次只能关注一个选项卡 (window)。当 运行 循环时,选择最后一个 URL 并执行那里的功能。

对于解决方案,您必须根据 URL 计数找到选项卡的数量,并在下一个完成后切换回每个 URL。

例如:

  • browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB) - 移动到新选项卡并积极处理它。(使用 Keys.SHIFT 作为后缀选项卡)
  • driver.switch_to.window(driver.window_handles[i]) - 使用选项卡计数(i).