python中使用的Regex给出未知结果

2024-04-25 01:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个脚本,使用regular expression从两个不同的站点查找电话号码。当我尝试用下面的模式在本地刮取两个电话号码时,它的工作是完美的。然而,当我在网站上尝试同样的方法时,它就不起作用了。它只获取两个未标识的数字19998211。你知道吗

这是我迄今为止尝试过的:

import requests, re

links=[
    'http://www.latamcham.org/contact-us/',
    'http://www.cityscape.com.sg/?page_id=37'
    ]

def FetchPhone(site):
    res = requests.get(site).text
    phone = re.findall(r"\+?[\d]+\s?[\d]+\s?[\d]+",res)[0]  #I'm not sure if it is an ideal pattern. Works locally though
    print(phone)

if __name__ == '__main__':
    for link in links:
        FetchPhone(link)

我希望的结果是:

+65 6881 9083
+65 93895060

这就是我所说的本地:

import re

phonelist = "+65 6881 9083,+65 93895060"

phone = [item for item in re.findall(r"\+?[\d]+\s?[\d]+\s?[\d]+",phonelist)]
print(phone)  #it can print them

Post脚本:电话号码不是动态生成的。当我打印文本时,我可以在控制台中看到numbers。你知道吗


Tags: importre脚本httpifwwwsitephone
2条回答

在下面的例子中,regex应该返回所需的输出

r"\+\d{2}\s\d{4}\s?\d{4}"

请注意,它可以应用于上述模式:

  • +65 6881 9083号
  • +65 93895060

在其他情况下可能不起作用

您正在使用\d+\s?\d+,它将匹配9 9991999,因为+量词允许第一个\d+抓取尽可能多的数字,同时将至少一个数字留给其他数字。一种解决方法是陈述你想要的特定的重复次数(比如Andersson的答案)。你知道吗

我建议您尝试regex101.com,它将突出显示以帮助您可视化regex匹配和捕获的内容。在那里你可以粘贴一个你想要搜索的文本的例子并调整你的正则表达式。你知道吗

相关问题 更多 >