1

I'm trying to scrape the text (dynamic) using selenium which is present as mentioned below in website. I searched all over the internet but I got how to scrape a text when it is present in separate div/p/span or any other tag only. Please help if you have any idea.

<div class='css-87uc0g e1tk4kwz1'>
    Text
    <span>
        4.5 
        <span> ::before </span>
    </span>
<div>

I want to extract only text here but that span tag is not allowing it.

Note: The value of text is dynamic.

1 Answer 1

2

Find the div element using following xpath and use javascript executor and get the first child value.

element=driver.find_element_by_xpath("//div[.//span[contains(.,'Rating')]]")
print(driver.execute_script('return arguments[0].firstChild.textContent;', element).strip()) 

Or you can simply replace the value.

element=driver.find_element_by_xpath("//div[.//span[contains(.,'Rating')]]")
print(element.text.replace(driver.find_element_by_xpath("//span[contains(.,'Rating')]").text,'').strip())
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for an idea, but is there more generic way to get the element's text itself while it can be different amount of elements inside that element?
@Eliyahu : It depends on how the html structured. Java scripts executor found very useful. If the html structure has new line </br> we can use python splitline() to get the value.
@Bidhya Pokharel : Please check the updated answer and let me know how this goes?
I'm sorry, I updated the question. There is no static text as ' Rating', I had just wrote it down to show there is some span tag. But I did it using the css class and then replaced the rating (4.5) as you mentioned. Thank you for sharing!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.