0

私は Python と Scrapy にかなり慣れていないので、このサイトはこれまで私のプロジェクトにとって非常に貴重なリソースでしたが、今は非常に単純に思える問題に行き詰まっています。私はおそらくそれについて間違った方法で考えています。私がやりたいことは、各行のデータがスクレイピングされた URL をリストする出力 CSV に列を追加することです。言い換えれば、テーブルを次のようにしたいのです。

item1    item2    item_url
a        1        http://url/a
b        2        http://url/a
c        3        http://url/b
d        4        http://url/b    

私はpsycopg2を使用して、データベースに保存された一連のURLを取得し、そこからスクレイピングしています。コードは次のようになります。

class MySpider(CrawlSpider):
    name = "spider"

    # querying the database here...

    #getting the urls from the database and assigning them to the rows list
    rows = cur.fetchall()

    allowed_domains = ["www.domain.com"]

    start_urls = []

    for row in rows:

        #adding the urls from rows to start_urls
        start_urls.append(row)

        def parse(self, response):
            hxs = HtmlXPathSelector(response)
            sites = hxs.select("a bunch of xpaths here...")
            items = []
            for site in sites:
                item = SettingsItem()
                # a bunch of items and their xpaths...
                # here is my non-working code
                item['url_item'] = row
                items.append(item)
            return items

ご覧のとおり、解析機能が現在オンになっている URL を取得するだけのアイテムを作成したかったのです。しかし、スパイダーを実行すると、「exceptions.NameError: global name 'row' is not defined.」というメッセージが表示されます。これは、Python が行を XPathSelector 関数内の変数として認識しないためだと思いますが、そのようなことはありますか? (私が言ったように、私は新しいです。) とにかく、私は立ち往生しています。

4

1 に答える 1