如何在Python中过滤Web浏览的搜索条件?

如何在Python中过滤Web浏览的搜索条件?,python,Python,我想做一个基本的搜索程序,向同事演示。但由于某些原因,我在搜索程序中应用“过滤器”时遇到了困难。现在,我正在过滤亚马逊和游戏,寻找一个伪工作环境。当我运行代码并搜索amazon.com时,它会显示“无效的搜索条件。请再试一次。”这是完美的。但在第二次尝试时,它仍然显示“无效的搜索条件。请重试。”但随后完成搜索。即使我没有搜索亚马逊或游戏。如何使代码做出适当的反应 例如: import webbrowser search=input('Search: ') while search == st

我想做一个基本的搜索程序,向同事演示。但由于某些原因,我在搜索程序中应用“过滤器”时遇到了困难。现在,我正在过滤亚马逊和游戏,寻找一个伪工作环境。当我运行代码并搜索amazon.com时,它会显示“无效的搜索条件。请再试一次。”这是完美的。但在第二次尝试时,它仍然显示“无效的搜索条件。请重试。”但随后完成搜索。即使我没有搜索亚马逊或游戏。如何使代码做出适当的反应

例如:

import webbrowser

search=input('Search: ')

while search == str('amazon') or str('games'):
  print('Invalid search criteria. Try again')

  if search != str('amazon') or str('games'):
    webbrowser.open('http://'+search)

您可以将代码更改为使用simple if else分支:

import webbrowser
while True:
    search=input('Search: ')
    if search == 'amazon' or search == 'games':
        print('Invalid search criteria. Try again')

    else:
        webbrowser.open('http://'+search)

另外,在搜索中将条件更改为“amazon”或在搜索中将条件更改为“games”可能是一个好主意为了更好地处理输入

首先,您不需要使用类似
str(“amazon”)的表达式将字符串转换为字符串

第二,如果
语句是

if search in ('amazon', 'games'):
第三,您可能希望您的程序在第一个正确答案后不停止,而是允许用户几乎无限地询问另一个和另一个,直到用户只需按Enter(=空字符串),因此您的程序可能是:

import webbrowser

while True:
    search=input('Search: ')
    if not search:                  # Means search is not empty
        break;                      # Jump from your infinite loop

    if search in ('amazon', 'games'):
        print('Invalid search criteria. Try again')
    else:
        webbrowser.open('http://'+search)

为什么要使用while循环?我希望代码不断告诉用户他们搜索的内容无效,而不是只允许一次搜索。您在错误的位置使用了while循环,请参阅pkqxdd的回答我仍然收到消息,我的搜索条件无效。即使我没有输入亚马逊或游戏。是什么导致了这个问题?