python scrapy使用時にエラー「TypeError: ‘FormRequest’ object is not iterable」が発生した場合の対処法

python scrapy使用時にエラー「TypeError: ‘FormRequest’ object is not iterable」が発生した場合の対処法

pythonで、scrapyにてFormRequest使用時にエラー「TypeError: ‘FormRequest’ object is not iterable」が発生した場合の対処法を記述してます。エラーメッセージ通り「iterable」になっていないため発生します。

環境

  • OS windows 11 Home
  • python 3.10.8

エラー全文

以下のFormRequestを使用してログインしようとしたコードで発生

from scrapy.http import FormRequest

class WcaSpider(scrapy.Spider):
    name = 'wca'
    allowed_domains = ['xxxx']
    start_urls = ['xxxx']

    def start_requests(self):
        login_url = 'xxxx'
        return FormRequest(login_url,
                            formdata={'username': 'xxxx', 'password': 'xxxx'},
                            callback=self.parse)

    def parse(self,response):
        pass

エラーメッセージ

--- <exception caught here> ---
  File "C:\Users\username\anaconda3\lib\site-packages\twisted\internet\defer.py", line 1660, in _inlineCallbacks
    result = current_context.run(gen.send, result)
  File "C:\Users\username\anaconda3\lib\site-packages\scrapy\crawler.py", line 102, in crawl
    start_requests = iter(self.spider.start_requests())
builtins.TypeError: 'FormRequest' object is not iterable

2023-01-17 18:50:04 [twisted] CRITICAL:
Traceback (most recent call last):
  File "C:\Users\username\anaconda3\lib\site-packages\twisted\internet\defer.py", line 1660, in _inlineCallbacks
    result = current_context.run(gen.send, result)
  File "C:\Users\username\anaconda3\lib\site-packages\scrapy\crawler.py", line 102, in crawl
    start_requests = iter(self.spider.start_requests())
TypeError: 'FormRequest' object is not iterable

原因

戻り値が「イテレータ」になっていないため

対処法

「イテレータ」に変更します。

    def start_requests(self):
        login_url = 'xxxx'
        return [FormRequest(login_url,
                            formdata={'username': 'xxxx', 'password': 'xxxx'},
                            callback=self.parse)]