Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

python - Find element in a script tag beautiful soup

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...