【发布时间】:2020-10-06 02:57:12
【问题描述】:
我正在尝试从网站响应中打印列表中找到的单词,否则如果未找到则打印“未找到”。但是我的脚本会打印它找到的单词。但它也会为列表中的每个项目打印“未找到”。如果列表中没有找到任何内容,我只需要它打印“未找到”。
我的脚本:
response = requests.post(URL, headers=Headers, cookies=Cookies, data=Data)
content = response.content
status_type = [b'Approved', b'Pending', b'Rejected', b'Issued']
for status in status_type:
if status in content:
print(status.decode())
if status not in content:
print("Not Found")
【问题讨论】:
-
一个对象要么在列表中,要么不在列表中。所以你的第二个语句应该使用
elif而不是if -
@Noah,实际上一个没有条件的
else也可以做到这一点,但问题实际上是它打印了 not found for each 状态不在内容中。我认为 OP 所追求的是仅在找到 none 时才打印 not found。 -
@paxdiablo ,哦,我明白他的意思了。
-
在列表中搜索一个项目是一种非常常见的算法,在网上很多地方都可以使用。请在此处发布问题之前研究该主题。
标签: python python-3.x list beautifulsoup