Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 刮痧:另一种避免大量尝试的方法_Python_Scrapy - Fatal编程技术网

Python 刮痧:另一种避免大量尝试的方法

Python 刮痧:另一种避免大量尝试的方法,python,scrapy,Python,Scrapy,我想问一个问题 当我使用css选择器时,extract()将使输出内容成为一个列表 因此,如果css选择器没有值 它将在终端中显示错误(如下所示),并且爬行器不会在我的json文件中获取任何项 item['intro'] = intro[0] exceptions.IndexError: list index out of range 所以我使用try和except检查列表是否存在 sel = Selector(response) sites = sel.css("div.co

我想问一个问题
当我使用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" 
我觉得我使用了很多尝试和例外,我不知道这是否是一个好方法。

请给我一点指导,谢谢你

你可以使用单独的函数提取数据。 e、 g对于文本节点,示例代码如下

    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"))

在“除外”中:使用项['link']=“无链接”,而不是仅打印消息。但您也可以打印消息