简体   繁体   English

python selenium如何从谷歌获取链接

[英]python selenium how to get link from google

How do I get a link from Google? 如何从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 (eg not www.stackoverflow.com). 我需要获取谷歌链接,而不是链接到该网站(例如,不是www.stackoverflow.com)。 It's highlighted on this image: 它在这张图片上突出显示:

在此输入图像描述

You maye have multiple issues here: First and third options are a not a valid xpath. 您可能在此处有多个问题:第一个和第三个选项不是有效的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: 如果您知道要选择的链接的名称,我建议使用find_element_by_link_text

     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 如果第一个语句抛出一个异常(最有可能的元素未找到 ),则可能需要等待元素显示在页面上,如所描述这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM