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'
3
  • Have a look at stackoverflow.com/q/9567069/8944057. Commented Feb 11, 2018 at 6:07
  • 1
    Can you sumup your Manual Step along with the relevant HTML please? Commented Feb 11, 2018 at 6:31
  • I have updated my answer , have a look Commented Feb 11, 2018 at 14:21

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

@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
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.