selenium - 使用 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 号码。
解决方案
根据前缀提取电话号码:
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
推荐阅读
- java - Java 通过另一个大小为 n 的布尔数组过滤数组
- perl - 为什么我不必对 atan2 等使用“使用 Math::Trig”?
- airflow - DAG 中的新任务阻止进一步的 DAG 执行
- regex - 正则表达式匹配特定模式中的所有空格分隔标记
- angularjs - 通过 Angular 11 中的路由路径发送数据
- java - Java 日期/时间解析示例中“2007-12-03T10:15:30.00Z”的意义是什么(如果有的话)?
- twilio - Authy API Webhook - 无效的签名响应
- java - 将带有字符串索引的运行数字添加到 Spark 中的数据帧?
- javascript - 获取并乘以 WooCommerce 产品格式的价格以插入 Javascript
- amazon-ec2 - pm2 start -i max run on 12 vcpu 买我的 ec2 只有 8 vcpu