如何使用硒Python在Google上单击第一个结果 [英] How to click on the first result on google using selenium python
本文介绍了如何使用硒Python在Google上单击第一个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在google结果上单击第一个结果.这是我的代码 我正在输入从csv文件读取的chennai craiglist的位置.因此,我确定有机结果中的第一个链接将是chennai.craiglist.org.但是我很安静,不确定如何执行此操作.
I am trying to click on the first result on the google result. Here is my code where I am entering chennai craiglist which is read from csv file. So I am sure the first link that come in the organic result will be chennai.craiglist.org. But I am quiet not sure about how to do this.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
class Browse(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://google.com/"
filename = 'test.csv'
line_number = 1
with open(filename, 'rb') as f:
mycsv = csv.reader(f)
mycsv = list(mycsv)
self.cityname=mycsv[line_number][0]
self.username=mycsv[line_number][1]
self.password=mycsv[line_number][2]
self.verificationErrors = []
def test_browse(self):
driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_id("gbqfq").send_keys(self.cityname)
我想知道这行之后会发生什么?
I wanna know what should come after this line?
更新
现在我给的是
driver.find_elements_by_xpath(".//*[@id='rso']//div//h3/a")[:1].click()
我不确定它是否可以工作.
I am not sure if it will work or not.
推荐答案
您选择的xpath
是好的",但可能不是最好的.
The xpath
you have chosen is 'ok' but probably not the best.
result = driver.find_elements_by_xpath("//ol[@id="rso"]/li")[0] //make a list of results and get the first one
result.find_element_by_xpath("./div/h3/a").click() //click its href
这篇关于如何使用硒Python在Google上单击第一个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文