Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python selenium单击第一个google搜索结果?_Python_Selenium - Fatal编程技术网

如何使用python selenium单击第一个google搜索结果?

如何使用python selenium单击第一个google搜索结果?,python,selenium,Python,Selenium,我正试图编写一个程序,点击出现的第一个谷歌搜索链接。我的代码是: from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Firefox() driver.get("https://www.google.com/") search = driver.find_element_by_name("q") search.clear()

我正试图编写一个程序,点击出现的第一个谷歌搜索链接。我的代码是:

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

driver = webdriver.Firefox()
driver.get("https://www.google.com/")
search = driver.find_element_by_name("q")
search.clear()
search.send_keys("bee movie script")
search.send_keys(Keys.RETURN)
time.sleep(3)
assert "No results found." not in driver.page_source
result = driver.find_element_by_xpath('/html/body/div[6]/div[3]/div[8]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3')
result.click()
我尝试了各种方法以获得结果,但自动化无法找到元素。我从inspect元素复制了xpath,但得到一个错误:

NoSuchElementException: Message: Unable to locate element: /html/body/div[6]/div[3]/div[8]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3

我是否做得不正确?我如何修复它?谢谢。

我找到了一个解决方案:

results = driver.find_elements_by_xpath('//div[@class="r"]/a/h3')  # finds webresults
results[0].click(). # clicks the first one

您可以使用下面的xpath和css来选择第n个链接

xpath: 使用索引

driver.find_element_by_xpath('(//div[@class="r"]/a)[1]').click()
如果要访问第一个匹配元素,只需使用
。find\u element\u xpath
,脚本将选择第一个元素,尽管有多个元素与给定的定位器策略匹配,无论是xpath、css还是其他

driver.find_element_by_css_selector("div.r a h3").click()