【问题标题】:How to create a pool of threads如何创建线程池
【发布时间】:2019-08-17 04:47:01
【问题描述】:

我正在尝试抓取此站点上的所有产品: https://www.jny.com/collections/jackets

它将获取所有产品的链接,然后将它们一一抓取。我正在尝试通过多线程来加速这个过程。代码如下:

def yield1(self, url):
    print("inside function")
    yield scrapy.Request(url, callback=self.parse_product)


def parse(self, response):
    print("in herre")
    self.product_url =  response.xpath('//div[@class = "collection-grid js-filter-grid"]//a/@href').getall()
    print(self.product_url)
    for pu in self.product_url:
        print("inside the loop")
        with ThreadPoolExecutor(max_workers=10) as executor:
             print("inside thread")
             executor.map(self.yield1, response.urljoin(pu))

它应该创建一个包含 10 个线程的池,每个线程将在 URL 列表上执行 yield1()。问题是没有调用 yield1() 方法。

【问题讨论】:

  • 你使用的是 asyncio 还是 concurrent.futures?
  • concurrent.futures
  • 您不应该捕获期货并在完成后对其进行迭代吗? docs.python.org/3/library/…
  • 给出这个错误:Request 类型的对象没有 len

标签: python multithreading scrapy python-multithreading


【解决方案1】:

yield1 是一个生成器函数。要让它产生一个值,你必须 调用 next 。 改变它,让它返回一个值

def yield1(self, url):
    print("inside function")
    return scrapy.Request(url, callback=self.parse_product)

警告:我对 Scrapy 一无所知。

Overview in the docs 表示请求是异步发出的。您的代码与这些文档中给出的示例不同。概述中的示例显示了使用response.followparse 方法中发出的后续请求。您的代码看起来像是在尝试从页面中提取链接,然后异步抓取这些链接并用不同的方法解析它们。由于看起来 Scrapy 会为您执行此操作并处理异步性(?)我认为您只需要在您的蜘蛛中定义另一个解析方法并使用 response.follow 来安排更多的异步请求。你不应该需要 concurrent.futures,the new requests should all be processed asynchrounously

我无法对此进行测试,但我认为您的蜘蛛应该看起来更像这样:

class TempSpider(scrapy.Spider):
    name = 'foo'
    start_urls = [
        'https://www.jny.com/collections/jackets',
    ]
    def parse(self, response):
        self.product_url =  response.xpath('//div[@class = "collection-grid js-filter-grid"]//a/@href').getall()
        for pu in self.product_url:
            print("inside the loop")
            response.urljoin(pu)
            yield response.follow(response.urljoin(pu), self.parse_product)

    def parse_product(self, response):
        '''parses the product urls'''

这假设 self.product_url = response.xpath('//div[@class = "collection-grid js-filter-grid"]//a/@href').getall() 做了它应该做的事情。

甚至可能有一个单独的 Spider 来解析后续链接。或者使用CrawlSpider


相关SO问答
Scraping links with Scrapy
scraping web page containing anchor tag using scrapy
Use scrapy to get list of urls, and then scrape content inside those urls(看起来很眼熟)
Scrapy, scrape pages from second set of links
many more

【讨论】:

  • 它似乎在工作,但现在它没有调用回调函数 parse_product
  • 这听起来像是一个不同的问题。这回答了你的问题吗?
  • 你怎么知道回调没有被调用?
  • 代码退出,在 parse_product 中甚至没有执行一条语句
猜你喜欢
  • 2015-03-28
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 2016-10-11
  • 2020-01-06
  • 1970-01-01
  • 2017-02-05
  • 2021-08-29
相关资源
最近更新 更多