Home > OS >  Python check if span class exists
Python check if span class exists

Time:11-12

So basically I want to get an output on boolean mode if a span class exists or no, but I don't know which libraries to use

<span >
  Smth
</span>

I have tried searching some tutorials for requests but I didnt find anything

CodePudding user response:

You can simply do this;

html = '<span >Smth</span>'

if html.find('span ') == -1:
    print(False)

else:
    print(True)

If you want to use any library then you can try beautifulsoup4

from bs4 import BeautifulSoup

html = '<span >Smth</span>'

soup = BeautifulSoup(html, "html.parser")

if soup.find('span', class_='Smth'):
    print(True)
else:
    print(False)

CodePudding user response:

If using BeautifulSoup to get a boolean response, you need to look for a all elements with a specific locator (so you need to use either find_all, or select), otherwise you get an error instead of a clean True/False. Here is a minimal example:

from bs4 import BeautifulSoup as bs

html = '<span >Smth</span>'

soup = bs(html, 'html.parser')

if soup.select('span[]'):
    print('success')
else:
    print('fail')

BeautifulSoup documentation: https://beautiful-soup-4.readthedocs.io/en/latest/

  • Related