0

我对 Python 和 Scrapy 还很陌生,到目前为止,这个网站对我的项目来说是一个非常宝贵的资源,但现在我遇到了一个看起来很简单的问题。我可能想错了。我想要做的是在我的输出 CSV 中添加一列,其中列出了每行数据被抓取的 URL。换句话说,我希望表格看起来像这样:

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

2

将开始请求生成不是放在类主体中,而是放在start_requests()

class MySpider(CrawlSpider):

    name = "spider"
    allowed_domains = ["www.domain.com"]

    def start_requests(self):
        # querying the database here...

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

        for url, ... in rows:
            yield self.make_requests_from_url(url)


    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select("a bunch of xpaths here...")

        for site in sites:
            item = SettingsItem()
            # a bunch of items and their xpaths...
            # here is my non-working code
            item['url_item'] = response.url

            yield item
于 2012-08-20T09:47:45.820 回答