1

How do I get a link from Google? I tried the following ways, but none of them worked:

  1. find_elements_by_xpath("//*[@class='r']/@href")
  2. driver.find_element_by_xpath("//a").get_attribute("href")
  3. driver.find_element_by_xpath("//a").get_attribute(("href")[2])

I am receiving "none"

I need to get google link, not link to the site (e.g. not www.stackoverflow.com). It's highlighted on this image:

enter image description here

timbre timbre
  • 12,648
  • 10
  • 46
  • 77
ömer g.
  • 41
  • 4
  • Try as `driver.get_element_by_css_selector("h3.r > a").get_attribute("href")` and let me know..:) – Saurabh Gaur Aug 28 '16 at 18:14
  • @SaurabhGaur 'WebDriver' object has no attribute 'get_element_by_css_selector' i tried "driver.find_element_by_css_selector" but response http://stackoverflow.com . i have to get other link , as i said – ömer g. Aug 29 '16 at 18:01
  • What do you mean other link??.. and yes it's just typo mistake it should be `driver.find_element_by_css_selector` – Saurabh Gaur Aug 29 '16 at 18:10
  • @SaurabhGaur please look at the picture. i need the right link. /url?sa=t&rct=j&... – ömer g. Aug 29 '16 at 18:16

1 Answers1

0

You maye have multiple issues here: First and third options are a not a valid xpath. Second options may find more than one matches, so it will return the first that fits, which is not necessarily the one you want. So I suggest:

  1. Make find specific enough to locate a proper element. I'd suggest find_element_by_link_text if you know the name of the link you are going to choose:

    link = driver.find_element_by_link_text('Stack Overflow')
    
  2. Given you chose the right link, you should be able to get the attribute:

    href = link.get_attribute('href')
    
  3. If the first statement throws an exception (most likely element not found), you may need to wait for the element to appear on the page, as described here

Community
  • 1
  • 1
timbre timbre
  • 12,648
  • 10
  • 46
  • 77