【问题标题】:Python If With no commands followed by a Else Syntax errorPython If 没有命令后跟 Else 语法错误
【发布时间】:2018-04-15 05:11:38
【问题描述】:

我正在编写一个基本的网页抓取代码,它基本上将获取帖子的日期和标题,如果日期 >= 存储在 SQL 数据库中的日期,并且标题 != 来自也存储在数据库中的标题,然后做一些事情。

执行时遇到语法错误。代码如下:

for i in web_results:
    py_newsdate = datetime.strptime(i.find('div', attrs={'class': "infoItem"}).find_all('p')[0].getText()[6:], '%d/%m/%Y')
    py_newstitle = i.find('h3').find('a')['title'] 

    if (py_newsdate < sql_latest[0][0] or py_newstitle == sql_latest[0][1]):
    else:
        py_newslink = i.find('h3').find('a')['href'] 
        web_results_final.append([py_newsdate, py_newstitle, py_newslink])

print(web_results_final)

这是错误:

  File "searcher", line 37
    else:
       ^
IndentationError: expected an indented block

我知道必须正确识别块,但我认为问题可能出在这个“空”if 上。

谢谢。

【问题讨论】:

标签: python syntax indentation


【解决方案1】:

块后面需要跟一些东西。如果你有一个想要留空的块,那么使用pass 语句:

if (py_newsdate < sql_latest[0][0] or py_newstitle == sql_latest[0][1]):
    pass
else:
    py_newslink = i.find('h3').find('a')['href'] 
    web_results_final.append([py_newsdate, py_newstitle, py_newslink])

无论您是尝试内联还是多行编写块,这都是正确的:

if 0: pass
else: print(2)

注意:else 块必须有一个新行。这不起作用:

if 0: pass; else: print(2)

【讨论】:

    【解决方案2】:

    如果你使用它会更有效,

    if not (py_newsdate < sql_latest[0][0] or py_newstitle == sql_latest[0][1]):
        py_newslink = i.find('h3').find('a')['href'] 
        web_results_final.append([py_newsdate, py_newstitle, py_newslink])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多