首页 > 解决方案 > 使用 Selenium (Java) 查找德国电话号码

问题描述

我正在尝试通过带有 Selenium Web 驱动程序 API 的正则表达式从德国网站获取 Telefon 号码(德语格式)。我的问题是我得到了一些误报,我还不能排除这些。有人可以帮我优化正则表达式吗?所以我确定我得到的是 100% 的电话号码。在代码中,Impressum 通常是联系方式的名称,这就是为什么我在网站上寻找“Impressum”这个词,然后单击它,然后下载字符串中的 html 正文。然后我使用正则表达式在 html 正文中查找电话号码。谢谢你。

  public void search() {
        jse = (JavascriptExecutor) driver;
        WebElement w = driver.findElement(By.partialLinkText("mpress"));
        if (w.getText().matches("Impressum" ) || w.getText().matches("impressum")){
            w.click();
        }
        impressum.setBody(driver.findElement(By.tagName("body")).getText());   // HTML-body download
    }

    @SuppressWarnings("Duplicates")
    public void TelRegex() {
        final String regex = "([\\+][0-9]{1,3} [ \\.\\-\\/])?  ([\\(][0-9]{1,6}[\\)])?  ([0-9 \\.\\-\\/]{10,20})$";
        final String string = impressum.getBody();

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }
    }

在代码中,Impressum 通常是联系方式的名称,这就是为什么我在网站上寻找“Impressum”这个词,然后单击它,然后下载字符串中的 html 正文。然后我使用正则表达式在 html 正文中查找电话号码。它给了我 fone 号码,但有时也有其他号码不是 fone 号码。

标签: seleniumweb-scrapingwebdriverweb-crawler

解决方案


根据前缀提取电话号码:

public void extractAllPhoneNumbers() {
    ArrayList<String> phoneNumbers = new ArrayList<String>();

    driver.get("https://www.vario-doser.de/");
    WebElement impressumLink = waitSec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='ueber-uns/impressum/']")));
    impressumLink.click();
    WebElement content = waitSec(driver, 5).until(ExpectedConditions.elementToBeClickable(By.id("content")));
    String[] contentText = content.getText().split("\\n");

    String[] prefixes = {"0180 / ", "09721 / "};

    for (String line: contentText) {
        for (String prefix: prefixes) {
            if (line.contains(prefix)) {
                phoneNumbers.add(line);
                System.out.println("Extracting: " + line.split(prefix)[1]);
            }
            else {
                System.out.println("Textline does not contain any of the prefixes.");
            }
        }
    }
    if (phoneNumbers.size() > 0) {
        System.out.println("Extracted phone numbers:");
        for (String phoneNumber: phoneNumbers) {
            System.out.println(phoneNumber);
        }
    }
    else {
        System.out.println("No phone number found.");
    }

}

但它包括传真。

...
Textline does not contain any of the prefixes.
Extracted phone numbers:
Tel.: 09721 / 533404
Fax: 09721 / 533405
Tel: 0180 / 60 05 85 0

推荐阅读