用python检查word是否在网页中出现两次

用python检查word是否在网页中出现两次,python,Python,我正在登录一个站点,然后搜索该站点。根据搜索结果,我在html中搜索,看是否匹配。这一切都很完美,除了网站上写着“xyz搜索结果”,这是我的搜索结果,所以当结果可能是负面的时候,我总是得到正面的结果。我当前的代码 ... Previous code to log in etc... words = ['xyz'] br.open ('http://www.example.com/browse.php?psec=2&search=%s' % words) html = br.respo

我正在登录一个站点,然后搜索该站点。根据搜索结果,我在html中搜索,看是否匹配。这一切都很完美,除了网站上写着“xyz搜索结果”,这是我的搜索结果,所以当结果可能是负面的时候,我总是得到正面的结果。我当前的代码

... Previous code to log in etc...

words = ['xyz']

br.open ('http://www.example.com/browse.php?psec=2&search=%s' % words)
html = br.response().read()

for word in words:
   if word in html:
      print "%s found." % word
   else:
      print "%s not found." % word
作为一个解决方案,我想检查这个词是否出现两次或两次以上,如果是,那么它是肯定的。如果它只出现一次,那么显然只是“xyz的搜索结果”被拾取,因此找不到它。我将如何调整我当前的代码以检查两次而不是一次

谢谢你可以试试这个

for word in words:
    if html.count(word)>1:
        #your logic goes here
范例

>>> words =['the.cat.and.hat']
>>> html = 'the.cat.and.hat'
>>> for w in words:
...       if html.count(w)>1:
...           print 'more than one match'
...       elif html.count(w) == 1:
...           print 'only one match found'
...       else:
...           print 'no match found'
...
only one match found
>>>

简而言之,您需要字符串中特定单词的出现次数。使用string.count()。请参阅。

作为另一种解决方案,您可以使用BeautifulSoup选择在哪个网站的部分(例如某个特定部分)进行单词搜索。Does。count单个单词或整个字符串。例如,如果words='the.cat.and.hat'和html='the.cat.and.hat和cat'匹配两次是因为它找到cat两次还是因为它只找到.cat.and.hat一次才匹配一次?
,它计算单个单词的数量,如果大小写是字符串列表,请参阅我前面的评论。谢谢。那么,如果words=['the.cat.and.hat']我如何让它只匹配整个句子'the.cat.and.hat'?你能修改你的答案吗?看起来源代码的实例比视觉网站的实例要多,而视觉网站的结果很混乱。谢谢你的帮助。