12

I have a google search result, something like

div class="rc"
    h3 class="r"
        <a href="somelink">
            <img id="idFOO" src="data:somethingFOO" style="...">
        </a>

I want to add somethingFOO (or data:somethingFOO) to a string using python & selenium. How can I do that?

cosminp
  • 258
  • 2
  • 4
  • 15
  • what do you mean you wan to add, do you mean you want to fetch this text and combine with string or you want to add something to this text ? – Gaurang Shah Jul 20 '17 at 13:21
  • I want to put "somethingFOO" in a string. For example I want to be able to do "return string" and the result to be "somethingFOO". – cosminp Jul 20 '17 at 13:23
  • what have you tried so far, and what's not working? – Gaurang Shah Jul 20 '17 at 13:25
  • I've tried myString=browser.find_element_by_class_name("r").text but I don't get what I want. I get some other text. I've tried find_element_by_id("idFOO).text and I get nothing. – cosminp Jul 20 '17 at 13:27
  • Possible duplicate of [accessing selenium web elements with python](https://stackoverflow.com/questions/8121886/accessing-selenium-web-elements-with-python) – JeffC Jul 20 '17 at 15:39

2 Answers2

37

what you are interested is not a text, it's an attribute with name src. so if you will do something like that, you won't get what you want.

find_element_by_id("idFOO").text

if your html is like this,

<input id="demo">hello world </input>

then the following code will give you hello world

driver.find_element_by_id("demo").text

and following code will give you demo

driver.find_element_by_id("demo").get_attribute("id")

so in your case, it should be

driver.find_element_by_id("idFOO").get_attribute("src")

Gaurang Shah
  • 11,764
  • 9
  • 74
  • 137
3

Try:

src = driver.find_element_by_xpath("//div[@class='rc]/h3[@class='r']/a/img").get_attribute("src")

P.S.- Used full available xpath to avoid duplicate conflicts on actual DOM.

Rahul Chawla
  • 1,048
  • 10
  • 15