Python If没有命令后跟Else语法

2024-09-28 01:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个基本的webscrapping代码,它基本上会得到一篇文章的日期和标题,如果日期>;=存储在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上

谢谢


Tags: 代码pyweb数据库标题sqliffind
3条回答

积木后面要有东西。如果有块要留空,请使用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)

如果你使用

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])
if (py_newsdate < sql_latest[0][0] or py_newstitle == sql_latest[0][1]):
    continue
else:
    py_newslink = i.find('h3').find('a')['href'] 
    web_results_final.append([py_newsdate, py_newstitle, py_newslink])

相关问题 更多 >

    热门问题