Python的Else和Pass

-1 投票
1 回答
1706 浏览
提问于 2025-04-18 08:08

嘿,我有一个小脚本,它应该检查一堆网页的代码,如果在某个页面找到了特定的字符串,就通过Pushbullet发送消息;如果没有找到,就什么也不做。

这是我现在的代码,能不能帮我修改一下,让它正常工作?我现在遇到的问题是if else的部分。

import urllib
import time
from pushbullet import Device

string = 'this is a test string'
b = 1
phone = Device('APIKEY', 'DeviceKEY')

while b <= 10:
    webpage = urllib.urlopen('http://thisisawebpage.com').read()
    website = urllib.urlopen('http://thisisawebsite.com').read()
    phone.push_note("String Found" , "String Found") if string in webpage else pass
    phone.push_note("String found in Website" , "String found in Website") if string in website else pass
    time.sleep(1800)

1 个回答

3

这里的 if-else 是一个表达式,而不是一个语句,所以你不能使用 pass。条件表达式是用来根据条件选择两个值中的一个;它并不是一个控制流程的语句。你应该使用一个合适的 if 语句。

if string in webpage:
    phone.push_note("String Found", "String Found")
if string in website:
    phone.push_note("String found in Website", "String found in Website")

如果你了解 Perl,Python 的条件表达式看起来和 Perl 的 if 语句修饰符很像,但它们并不相同。在 Perl 中,像这样的写法

# This is pseudo-Perl; there is no `in` operator and the Perl replacement
# depends heavily on what $webpage actually is
$phone->push_note("String Found", "String Found") if $string in $webpage;

是可以工作的,但在 Python 中就不行。

撰写回答