0

Yes, I read other threads like: Styling multi-line conditions in 'if' statements?

I have this code and I want to check if a specific texts exists on the given page. The code does only work with one condition for some reasons, not with 2 or more.

import requests

r = requests.get('http://example.com/')

if 'ghcjdfghfgh' or 'fgxhdfghdfyh' in r.text:
    print ('Yes')
else:
    print ('No')

It says yes, even though it not true. I tried the same code with a comma instead of the "or" but still, the same issue.

import requests
r = requests.get('http://example.com/')

if 'ghcjdfghfgh','fgxhdfghdfyh' in r.text:
    print ('Yes')
else:
    print ('No')
JohnsonR
  • 9
  • 4

3 Answers3

0

Try this:

if 'ghcjdfghfgh' in r.text or 'fgxhdfghdfyh' in r.text:
    print ('Yes')
else:
    print ('No')

Or if you want to extend it, use this answer's technique:

a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]

if any(x in a_string for x in matches):
DMart
  • 2,401
  • 1
  • 14
  • 19
0
if 'ghcjdfghfgh' or 'fgxhdfghdfyh' in r.text:
    print ('Yes')
else:
    print ('No')

this checks if ghcjdfghfgh true or 'fgxhdfghdfyh' in r.text is true , as all string is true by default. ghcjdfghfgh is true

so this equate always true.

If you want to test if any of the string in r.text you can use:

if any(x in r.text for x in ['ghcjdfghfgh','fgxhdfghdfyh']):
    print("hi")
PDHide
  • 18,113
  • 2
  • 31
  • 46
0

The problem is that in this statement:

if 'ghcjdfghfgh' or 'fgxhdfghdfyh' in r.text:

you are actually asking 2 different things; (I): if 'ghcjdfghfgh' is true! (II): if 'fgxhdfghdfyh' is in r.text. the thing is that (I) is always true; therefore you get 'yes' no matter what!

I can think of 3 ways to get your desired result: First::

if 'ghcjdfghfgh' in r.text or 'fgxhdfghdfyh' in r.text:
    print ('Yes')
else:
    print ('No')

Second::

if r.text.find('ghcjdfghfgh') != -1 or r.text.find('fgxhdfghdfyh') != -1:
    print ('Yes')
else:
    print ('No')

Third ( THE BEST ONE )::

if any(partial_text in r.text for partial_text in ['ghcjdfghfgh','fgxhdfghdfyh']):
    print('Yes')
else:
    print('No')
KOLab
  • 31
  • 4