简体   繁体   English

在脚本标记美丽汤中查找元素

[英]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谢谢

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.问题是str.find方法返回原始字符串中 substring 的索引(如果未找到,则返回-1 ),因此s只是索引列表。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM