簡體   English   中英

如何使用 selenium 和 python 獲取谷歌搜索結果鏈接

[英]How to fetch google search results links using selenium and python

我正在嘗試獲取所有搜索結果鏈接並打印出來。 我發現的問題是我無法使用單個搜索結果的 xpath 進行迭代,因為

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

是一個結果,下一個結果的鏈接是

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

div 的索引值是在整個結果中迭代的值。 目前我只能用 div 的索引值獲取一個鏈接。 我想獲取所有結果並將 append 提取到列表中以進行進一步處理。 幫我解決這個問題

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)

創建一個計數器 i 並將其放在您的 xpath 中。 假設我是 integer 計數器,然后在 xpath 中使用將其轉換為字符串

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM