Ajitesh Singh
Ajitesh Singh

Reputation: 461

Scraping - How to find tag of a webelement using selenium in python

For instance if i have a webelement and i want to check if it contains h2 tag or not.. is it possible? if yes then how

from selenium import webdriver
import re
import pandas as pd
from bs4 import BeautifulSoup
chrome_path = r"C:\Users\ajite\Desktop\web scraping\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get('....')

header = driver.find_element_by_xpath('/html/body/div[5]/div[2]/div/ol/li[1]/div/div/div[1]/h2')

if header.contains('h2'):
    print("successful")
else:
    print("unsuccesful")

header variable contains h2 tag but i cannot use header.contains since its a webelement and not a text

Error

Traceback (most recent call last):
  File "test2.py", line 11, in <module>
    if header.contains('h2'):
AttributeError: 'WebElement' object has no attribute 'contains'

Upvotes: 0

Views: 3631

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193338

If you want to check if the webelement contains ` tag or not you can use the following code block :

header = driver.find_element_by_xpath('/html/body/div[5]/div[2]/div/ol/li[1]/div/div/div[1]/h2')
if 'h2' in header.tag_name:
    print("successful")
else:
    print("unsuccesful")

Upvotes: 0

Pradeep hebbar
Pradeep hebbar

Reputation: 2267

You can use the tag_name method to get the tag name of the webelement like below.

from selenium import webdriver
chrome_path = r"path"
driver = webdriver.Chrome(chrome_path)
driver.get("http://www.google.co.in")
print ("Launching chrome")
element = driver.find_element_by_xpath('//*[@title="Search"]')
print("element.tag_name "+element.tag_name)
if element.tag_name == "input":
    print("successful")
else:
    print("unsuccesful")
driver.quit()

Upvotes: 2

Related Questions