0

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'
Ajitesh Singh
  • 401
  • 2
  • 5
  • 14

2 Answers2

2

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()
Pradeep hebbar
  • 2,147
  • 1
  • 9
  • 14
  • @RatmirAsanov , its not about python or java , its about selenium. if selenium provide some method for java means it obviously provide in python too. I have updated and verified my code – Pradeep hebbar Feb 11 '18 at 14:20
0

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")
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352