3

I am trying to get src(URL) link of main image from xkcd.com website. I am using the following code but it returns something like session="2f69dd2e-b377-4d1f-9779-16dad1965b81", element="{ca4e825a-88d4-48d3-a564-783f9f976c6b}"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://xkcd.com')
assert 'xkcd' in browser.title

idlink= browser.find_element_by_id("comic")

#link = idlink.get_attribute("src") ## print link prints null

print idlink

using xpath method also returns same as above.

Guy
  • 46,488
  • 10
  • 44
  • 88
feature sky
  • 171
  • 4
  • 15

2 Answers2

2

browser.find_element_by_id returns web element, and that is what you print. In addition, the text you want is in child element of idlink. Try

idlink = browser.find_element_by_css_selector("#comic > img")
print idlink.get_attribute("src")

idlink is now web element with img tag who has parent with comic ID. The URL is in src so we want that attribute.

Guy
  • 46,488
  • 10
  • 44
  • 88
2

Building off the answer here

You need to:

  1. Select the img tag (you're currently selecting the div)
  2. Get the contents of the source attribute of the img tag

    img_tag = browser.find_element_by_xpath("//div[@id='comic']/img")
    print img_tag.get_attribute("src")
    

The above should print the URL of the image

More techniques for locating elements using selenium's python bindings are available here

For more on using XPath with Selenium, see this tutorial

Community
  • 1
  • 1
jeyoor
  • 938
  • 1
  • 11
  • 20
  • thanks Ur answer works as well. it should be get_attribute("src") up there. – feature sky Jan 14 '16 at 18:38
  • thanks for the upvote and the edit. :) For me, XPath has been the way to go when working with Selenium... the extra precision has saved my bacon many a time. – jeyoor Jan 14 '16 at 18:38