Python 条件语句(IF, ELSE)缩进异常

-1 投票
3 回答
2726 浏览
提问于 2025-04-17 19:25

我正在做我的第一个Python项目,使用的是Scrapy.org这个框架。我想用一个IF语句来判断价格是否为空,这样就不会把空值存储到我的CSV文件里。

但不知为什么,我遇到了一个缩进错误。

IndentationError: expected an indented block

这个IF语句在这段代码的最后。

谢谢大家抽时间来帮我!

代码:

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from craigslist_sample.items import CraigslistSampleItem

class MySpider(BaseSpider):
name = "craig"
allowed_domains = ["craigslist.org"]
start_urls = [
'http://longisland.craigslist.org/search/sss?sort=date&query=raptor+660&srchType=T',
'http://newyork.craigslist.org/search/sss?zoomToPosting=&query=raptor+660&srchType=T&minAsk=&maxAsk=&sort=date',
'http://hudsonvalley.craigslist.org/search/sss?zoomToPosting=&query=raptor+660&srchType=T&minAsk=&maxAsk=&sort=date',
'http://newjersey.craigslist.org/search/sss?zoomToPosting=&query=raptor+660&srchType=T&minAsk=&maxAsk=&sort=date',
'http://hartford.craigslist.org/search/sss?zoomToPosting=&query=raptor+660&srchType=T&minAsk=&maxAsk=&sort=date'
]

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select("//p")
    items = []
    for titles in titles:
        item = CraigslistSampleItem()
        #item["date"] = titles.select('span[@class="itemdate"]/text()').extract()
        item ["title"] = titles.select("a/text()").extract()
        item ["link"] = titles.select("a/@href").extract()
        item ["price"] = titles.select('span[@class="itempnr"]/span[@class="itempp"]/text()').extract()
        if not items ["price"]:
            #do nothing
        else:
            items.append(item)
    return items

3 个回答

2

如果你的if语句没有任何操作,而你只在用else,那你可能想用if条件的反面。假如你只是想测试一下,你需要在if里面加一个pass

if True:
  pass  # just a comment here does not work
else:
  dostuff()
3

问题是这样的:

    if not items ["price"]:
        #do nothing
    else:
        items.append(item)

...在需要缩进语句的地方,你不能只写一个注释。Python 有一个专门为这种情况准备的关键字——pass

    if not items ["price"]:
        #do nothing
        pass
    else:
        items.append(item)
3

ifelsefordef等这些关键字后面必须跟着一段代码块。单纯的注释是不算的。这就是pass语句的用处:

if not item["price"]:
    pass
else:
    items.append(item)

那么,为什么不直接把条件反过来呢?

if item["price"]:
    items.append(item)

撰写回答