简体   繁体   中英

How to fetch google search results links using selenium and python

I am trying to fetch all the search results link and print it. The problem I found is I am not able to iterate using the xpath of the individual search results because

elems = driver.find_elements_by_xpath('div[2]/div/div[1]/a')

is one result and the next result's link is

elems = driver.find_elements_by_xpath('div[3]/div/div[1]/a')

The index value of div is what iterates throughout the results. Currently I am able to fetch only one link with the index value of div. I want to fetch all of the results and append it to a list for further processing. Help me out on this one

driver = webdriver.Chrome()
driver.get('http://www.google.com')

search_input = driver.find_element_by_name('q')
search_input.send_keys('stackoverflow')
search_input.send_keys(Keys.ENTER)
results = []
elems = driver.find_elements_by_xpath('div[2]/div/div[1]/a')
for elem in elems:
    href = elem.get_attribute('href')
    print(href)
    results.append(href)

Create a counter i and place it in your xpath. Suppose i is integer counter before using it in xpath convert it into string using

  string= str(i)
  elems = driver.find_elements_by_xpath("div['"+ string +"']/div/div[1]/a")
    import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.util.List;

public class GooglesearchTests {

    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver83\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.google.com/");
        driver.findElement(By.name("q")).sendKeys("Testing");
        Thread.sleep(Long.parseLong("1000"));
        List<WebElement> LIST = driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']"));
        System.out.println(LIST.size());


        for (int i = 0; i < LIST.size(); i++)
        {
            //System.out.println(LIST.get(i).getText());
            if (LIST.get(i).getText().contains("testing types"))
            {
                LIST.get(i).click();
                break;
            }
        }
    }
}


This is java code for google search results 


every day google page elements are changing ( What i am doing is open google and type testing and store all results in list and pick "Testing Type" from list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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