简体   繁体   中英

Python with bs4 finding element in <script>

I'm trying to access a value in in an html / xml with bs4 but really can't find it. This is an example of what i'm trying to get:

<script>
  item1 = "a"
  item2 = "b"
</script>

I tried with this code:

for item in html.find_all('script'):
  if 'item1' in item:
    print(item)

but it doesn't work (nothing gets printed)... Could anyone give a help with this? Thank ua lot in advance

Add .text and it prints the content of each script .

from bs4 import BeautifulSoup

scripts = '''
<script>
  item1 = "a"
  item2 = "b"
</script>
'''

html = BeautifulSoup(scripts)

for item in html.find_all('script'):
  if 'item1' in item.text:
    print(item.text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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