【问题标题】:Extract URLs from a google search page从谷歌搜索页面中提取 URL
【发布时间】:2016-02-02 05:08:01
【问题描述】:

我正在尝试从谷歌搜索页面中提取(前 5 个)网址。我尝试使用 selenium web 驱动程序提取它。我打开了firefox,页面也加载了,但正则表达式与页面上的url不匹配。如何获取提取的网址?

到目前为止,我使用了以下代码:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openqa.selenium.WebDriver;
import org.openga.selenium.firefox.FirefoxDriver;

public class Weburlext {

public static void main (String[] args){

String line = null;
Webdriver driver = new FirefoxDriver();
driver.ger("http://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sample%20data");

String regex="@^(http\\:\\/\\/|https\\:\\/\\/)?([a-z0-9][a-z0-9\\-]*\\.)+[a-z0-9][a-z0-9\\-]*$@i";
Pattern p = Pattern.compile(regex,pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(line);

System.out.print(line);

driver.quit();

}
}

【问题讨论】:

  • Don't do this,您的 IP 有被 Google 屏蔽的风险。使用 Google API 自动访问 Google 搜索结果。
  • 在您提供的代码中,行始终为空。
  • 你必须先检查你的正则表达式。 regexpal.com

标签: java regex selenium webdriver extraction


【解决方案1】:

我很好奇您为什么使用正则表达式来匹配 PageSource 中的 http 模式。使用 Selenium 查找前 5 个结果的正确方法是查找结果元素,然后获取属性“href”。见以下代码:

driver.get("https://www.google.com.ph/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sample%20data");

List<WebElement> results = driver.findElements(By.cssSelector("div[class='rc'] > h3 > a"));
results.forEach(e -> System.out.println(e.getAttribute("href")));

【讨论】:

    猜你喜欢
    • 2013-01-30
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2012-08-19
    • 2022-09-09
    • 2012-10-19
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多