I want to get the values contained in the span class with value "indigo-text descfont" for the following:
<div id="WineDetailContent"> event
<span >...</span>
<span >Alsace</span>
<br>
<span >...</span>
<span >2014</span>
<br>
</div>
So that I get Alsace and 2014. I have tried using the following:
details = driver.find_element_by_xpath("//div[starts-with(@id,'WineDetailContent')]")
res = details.find_element_by_xpath("//span[starts-with(@class,'indigo-text descfont')]")
print(res.text)
But it only returns the first needed value, i.e. Alsace. How is it possible to get 2014 as well?
CodePudding user response:
As per the HTML:
<div id="WineDetailContent">
...
<span >Alsace</span>
<br>
...
<span >2014</span>
<br>
</div>
Both the desired texts are within the decendants <span >
of their ancestor <div id="WineDetailContent">
Solution
To print the texts from the <span >
elements you can use list comprehension and you can use either of the following locator strategies:
Using CSS_SELECTOR:
print([my_elem.text for my_elem in driver.find_elements(By.CSS_SELECTOR, "div#WineDetailContent span.indigo-text.descfont")])
Using XPATH:
print([my_elem.text for my_elem in driver.find_elements(By.XPATH, "//div[@id='WineDetailContent']//span[@class='indigo-text descfont']")])
CodePudding user response:
find_element_by_xpath
return single WebElement. You need to use find_elements_by_xpath
to select both elements:
details = driver.find_element_by_xpath("//div[@id ='WineDetailContent']")
res = details.find_elements_by_xpath("./span[@class = 'indigo-text descfont']")
for i in res:
print(i.text)