0

I am new to beautiful soup, and I'm trying to find a way to search if an element exists within the script tag, but I keep getting not found when it's clearly there. Can you please help me with what's wrong with my line of code.

mykeyword = [element.text for element in soup.find_all("script")]
s = [element.find('cookie.indexOf') for element in mykeyword ]

if  'cookie.indexOf' in s:
    print('exist')
else:
    print('not found')

Thanks

Piyush Kumar
  • 120
  • 8
Justine
  • 105
  • 1
  • 17
  • I am confused. ` –  Jan 06 '21 at 17:28
  • the [`str.find`](https://docs.python.org/3/library/stdtypes.html#str.find) method returns the index of the found substring (or -1 if it wasn't found). – Roy Cohen Jan 06 '21 at 17:31
  • Rather than element (which is confusing re html), it looks like you are searching for a substring within a string? Please update the question with the relevant html. – QHarr Jan 07 '21 at 05:10

1 Answers1

0

The priblem is that the method str.find returns the index of the substring in the original string (or -1 if it's not found) so s is just a list of indexes. Instead you might want to do something like:

s = [element for element in mykeyword if 'cookie.indexOf' in element]

and then check if the list is empty like this:

if len(s) != 0: print('exist')
else: print('not found')
Roy Cohen
  • 1,540
  • 1
  • 5
  • 22
  • see [this SO quastion](https://stackoverflow.com/q/53513/14160477) for other ways to check if a list is empty in python. – Roy Cohen Jan 06 '21 at 17:38
  • I followed this and I still get the same not found. When i did print the source, I can see that the but the s line of code, is not seeing it, and keep returning not found. I was testing for this site theblondeabroad.com – Justine Jan 07 '21 at 09:18
  • @Justine try printing `mykeyword` to check if it has the relavent strings. Also, I couldn't find the docs for `.text`, but I did find `.get_text()` and `.string`, maybe those will work. – Roy Cohen Jan 07 '21 at 14:44