scrapy:另一种避免大量try except的方法

0 投票
1 回答
699 浏览
提问于 2025-04-18 18:40

我想问一个问题
当我使用 CSS 选择器时,extract() 会把输出的内容变成一个列表
所以如果这个 CSS 选择器没有找到值
终端就会显示错误(像下面这样),而且爬虫不会在我的 JSON 文件里获取到任何项目

item['intro'] = intro[0]
exceptions.IndexError: list index out of range

所以我使用了 try 和 except 来检查这个列表是否存在

    sel = Selector(response)
    sites = sel.css("div.con ul > li")
    for site in sites:
        item = Shopping_appleItem()
        links = site.css("  a::attr(href)").extract()
        title = site.css("  a::text").extract()
        date = site.css(" time::text").extract()

        try:
            item['link']  = urlparse.urljoin(response.url,links[0])
        except:
            print "link not found" 
        try:
            item['title'] = title[0]       
        except:
            print "title not found" 
        try:
            item['date'] = date[0]       
        except:
            print "date not found" 

我觉得我用了很多 try 和 except,但我不知道这样做是否合适。
请给我一点指导,谢谢

1 个回答

1

你可以用一个单独的函数来提取数据。
比如说,对于文本节点,这里有个示例代码。

    def extract_text(node):
        if not node:
            return ''
        _text = './/text()'
        extracted_list = [x.strip() for x in node.xpath(_text).extract() if len(x.strip()) > 0]
        if not extracted_list:
            return ''
        return ' '.join(extracted_list)

然后你可以这样调用这个方法。

    self.extract_text(sel.css("your_path"))

撰写回答