【问题标题】:How to scrape mobile phone numbers using beautifulsoup如何使用beautifulsoup 抓取手机号码
【发布时间】:2020-03-01 09:05:02
【问题描述】:

我只想抓取以下格式的手机:

+1 NXX-NXX-XXXX

N=digits 2–9, X=digits 0–9

+1 is the country code that includes the US, there are 17 other countries, e.g., Canada, Caribbean Islands.

假设我们需要找到以 986 和 965 等开头的每个数字(我们有一组这样的数字)作为第一个 NXX。

这是我获取电子邮件的代码:

    email = soup(text=re.compile(r'[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*'))

    _emailtokens = str(email).replace("\\t", "").replace("\\n", "").split(' ')

    if len(_emailtokens):
        print([match.group(0) for token in _emailtokens for match in [re.search(r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)", str(token.strip()))] if match])

但我需要更改它才能获得手机。

【问题讨论】:

  • 您尝试过更改正则表达式吗?
  • 亲爱的@Phix,我不知道该怎么做。
  • 您尝试在什么文本中查找数字?也许有更好的方法来获得它。
  • 亲爱的@furas,我的目的是从网页及其内容中查找数字。

标签: python regex python-3.x web-scraping beautifulsoup


【解决方案1】:

假设您已经编写了一个 scraper 来将您的数字字符串(移动和非移动)存储在一个列表中(在您的情况下,您很可能已经将数字拆分为一个基于在您的代码上),那么下面的 sn-p 代码(使用正则表达式)可能会对您有所帮助。

代码

import re

#NXX-NXX-XXXX
#NXX 986 or 965
#N=digits 2–9, X=digits 0–9

#here is the regex pattern you need
pattern = r'(?=[2-9]{1}[0-9]{2}-[2-9]{1}[0-9]{2}-[0-9]{4}$)((?P<hello>986.+)|(?P<world>965.+))'

#Note: give your groups (986 and 965) a sensible name, I am using hello and world for demonstration

sent = ['986-233-8901', '965-345-8745', '123-456-7890', '986-134-5987', '1234', '$5@67^73']
#Matched, Matched, None, None, None, None

regexp = re.compile(pattern)

#the matched results
result = [regexp.match(item) for item in sent]
#change to regexp.search() if needed

#a way to retrieve group elements with prefix 986 (group hello)
hello_group = [item.group('hello') for item in result if item is not None]

输出

print(result)
#[<re.Match object; span=(0, 12), match='986-233-8901'>, <re.Match object; span=(0, 12), match='965-345-8745'>, None, None]

print(hello_group)
#['986-233-8901', None]

【讨论】:

  • 亲爱的@QuantStats,非常好的代码。现在我的问题是如何从网页中发送这个数组(我的意思是哪种类型的 html 标签可能更适合用作我们发送列表中的候选者)。
  • @WilliamJohnson 这取决于您要从中报废的 html 的结构。例如,如果可行,您可以通过直接调用 bs.find_all('a', text=re.compile(pattern)) 来避免发送此数组。我希望它有所帮助。
  • 亲爱的@QuantStats,感谢您的宝贵意见,我想使用这种方法,但不幸的是,手机号码可能会在每个标签中找到,我需要检查所有 li 标签,也许还有 p 标签还有链接(td div li ap)等。
  • @WilliamJohnson 我想我明白你的意思。如果您在此处张贴您的网址,其他人可能会帮助您编写刮板。
  • 仅供参考,它是 scraper(和 scrapingscrapedscrape)而不是 scrapper。 “废弃”意味着像垃圾一样扔掉:-(
猜你喜欢
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 2018-08-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多