Michael Esteves
Michael Esteves

Reputation: 1485

Check if word appears twice in webpage with python

I'm logging into a site and then searching the site. From the results I'm searching through the html and seeing if I get a match. It all works perfectly except for the fact that the site says "Search results for xyz" which is picked up by my search so I always get a positive result when it could be negative. My current code

... 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

As a solution I would like to check if the word appears twice or more and if so then it is positive. If it appears only once then it is obviously just the "Search results for xyz" that is being picked up so it is not found. How would I go about adapting my current code to check for two occurrences and not just one?

Thanks

Upvotes: 3

Views: 3405

Answers (2)

RanRag
RanRag

Reputation: 49567

you can try this,

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

Example

>>> 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
>>>

Upvotes: 3

Tejas Patil
Tejas Patil

Reputation: 6169

In short you want the count of occurrences of a particular word in a string. Use string.count(). See This.

Upvotes: 0

Related Questions