Selenium webdriver click google search

后端 未结 7 921
情话喂你
情话喂你 2021-02-01 07:06

I\'m searching text \"Cheese!\" on google homepage and unsure how can I can click on the searched links after pressing the search button. For example I wanted to click the third

7条回答
  •  隐瞒了意图╮
    2021-02-01 08:02

    There would be multiple ways to find an element (in your case the third Google Search result).

    One of the ways would be using Xpath

    #For the 3rd Link
    driver.findElement(By.xpath(".//*[@id='rso']/li[3]/div/h3/a")).click();
    #For the 1st Link
    driver.findElement(By.xpath(".//*[@id='rso']/li[2]/div/h3/a")).click();
    #For the 2nd Link
    driver.findElement(By.xpath(".//*[@id='rso']/li[1]/div/h3/a")).click();
    

    The other options are

    By.ByClassName 
    By.ByCssSelector 
    By.ById
    By.ByLinkText
    By.ByName
    By.ByPartialLinkText 
    By.ByTagName 
    

    To better understand each one of them, you should try learning Selenium on something simpler than the Google Search Result page.

    Example - http://www.google.com/intl/gu/contact/

    To Interact with the Text input field with the placeholder "How can we help? Ask here." You could do it this way -

    # By.ByClassName 
    driver.findElement(By.ClassName("searchbox")).sendKeys("Hey!");
    # By.ByCssSelector 
    driver.findElement(By.CssSelector(".searchbox")).sendKeys("Hey!");
    # By.ById
    driver.findElement(By.Id("query")).sendKeys("Hey!");
    # By.ByName
    driver.findElement(By.Name("query")).sendKeys("Hey!");
    # By.ByXpath
    driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("Hey!");
    

提交回复
热议问题