0

I want to extract all h2 elements of the div element. The code that I've used is this:

browser = webdriver.Chrome()
browser.get("https://www.mmorpg.com/play-now")
time.sleep(2)
item_list_new=[]
link = browser.find_element_by_xpath("//div[@class='freegamelist']")
names = link.find_element_by_tag_name('h2')
x = names.text
item_list_new.append(x)
print(item_list_new)

But when I run this, I only get the first 'h2' element of the div element. Can somebody tell me what am I doing wrong and also please guide me with the correct way of doing it? Thanks in advance.

0

3 Answers 3

1

you need to write names = link.find_elements_by_tag_name('h2')

Your code should be

browser = webdriver.Chrome()
browser.get("https://www.mmorpg.com/play-now")
time.sleep(2)
item_list_new=[]
link = browser.find_element_by_xpath("//div[@class='freegamelist']")
names = link.find_elements_by_tag_name('h2')
x = names.text
item_list_new.append(x)
print(item_list_new)

find_element_by_tag_name gives the first element and find_elements_by_tag_name gives all the matching elements

Sign up to request clarification or add additional context in comments.

Comments

0

Try to get all header values as below:

link = browser.find_element_by_xpath("//div[@class='freegamelist']")
names = link.find_elements_by_tag_name('h2')
item_list_new = [x.text for x in names]
print(item_list_new)

or you can simplify

names = browser.find_elements_by_xpath("//div[@class='freegamelist']//h2")
item_list_new = [x.text for x in names]
print(item_list_new)

Comments

0

You actually want to use the function find_elements_by_tag_name that sounds almost similar, as pointed out here.

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.