Reputation: 185
I have a html file:
<div class="panel-heading">
Some Text1
<strong>Hello</strong>
</div>
<div>
Some Text2
Some Text3
<strong>
Hi1
Hi2
</strong
I want to print only Hello in my python script using selenium, so I tried:
element = driver.find_element_by_xpath("//div[@class='panel-heading']")
for element in driver.find_elements_by_tag_name('strong'):
print (element.text)
The result is:
Hello
Hi1
Hi2
But I want only:
Hello
Upvotes: 0
Views: 152
Reputation: 12255
You did small mistake in your code, you get div
with panel-heading
but in the loop you iterate throw all elements with tag strong
in DOM. Perhaps, here how you wanted it to be:
divElement = driver.find_element_by_xpath("//div[@class='panel-heading']")
for element in divElement.find_elements_by_tag_name('strong'):
print (element.text)
But div
with panel-heading
contains only one span
and strong
, you can get it with css selector:
strongText = driver.find_element_css_selector(".panel-heading strong").text
Upvotes: 0
Reputation: 73460
You can use next
:
for element in driver.find_elements_by_tag_name('strong'):
print(next(element.text for element in driver.find_elements_by_tag_name('strong')))
Or less cryptic and more robust if there is no such element, just break
the loop after the print:
for element in driver.find_elements_by_tag_name('strong'):
print(element.text)
break
Upvotes: 0
Reputation: 52665
You can simply use
element = driver.find_element_by_xpath("//div[@class='panel-heading']")
print(element.find_element_by_tag_name('strong').text)
to print first strong
text from required div
Note that for element in driver.find_elements_by_tag_name('strong')
means to iterate over all strong
nodes on page. You need to replace driver
with element
to iterate over descendant strong
s of defined WebElement:
for strong in element.find_elements_by_tag_name('strong'):
print(strong.text)
Upvotes: 0
Reputation: 313
Your code give you list. So simply use first element of the list, which give you "Hello".
element = driver.find_elements_by_tag_name('strong')[0]
Upvotes: 1