python 爬取页面并解析所有电话号码
时间: 2023-08-12 08:34:03 浏览: 62
可以使用Python中的requests和BeautifulSoup库来实现页面爬取和解析电话号码。
首先,使用requests库发送HTTP请求获取网页内容:
```python
import requests
url = "https://example.com" # 替换为要爬取的网页链接
response = requests.get(url)
if response.status_code == 200: # 请求成功
html = response.text # 获取网页内容
```
接下来,使用BeautifulSoup库解析HTML文档,提取所有电话号码:
```python
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html, "html.parser") # 解析HTML文档
tel_pattern = re.compile(r"\b\d{3}-\d{8}\b|\b\d{4}-\d{7}\b") # 匹配电话号码的正则表达式
tel_set = set() # 用set来去重
# 查找所有文本节点,并在其中匹配电话号码
for text_node in soup.find_all(text=True):
tel_list = tel_pattern.findall(text_node)
if tel_list:
tel_set.update(tel_list)
for tel in tel_set:
print(tel)
```
这里使用了正则表达式`\b\d{3}-\d{8}\b|\b\d{4}-\d{7}\b`来匹配电话号码,其中`\b`表示单词边界,`\d`表示数字,`{3}`和`{8}`表示匹配3位和8位数字,`|`表示或,`\d{4}-\d{7}`表示匹配4位和7位数字。使用set来去重,最后输出所有电话号码。