如何使用BeautifulSoup提取CSS生成内容中的手机号数据?
提取JustDial手机号的解决方案
JustDial把手机号拆分为单个数字,每个数字对应一个带:before伪元素的CSS类,存储在content属性里。要获取完整手机号,需先抓取并解析页面的CSS样式,再匹配HTML元素的类来提取对应数字。
实现步骤
- 抓取页面CSS样式:提取页面内
<style>标签的内容,若存在外部CSS链接则额外抓取对应资源。 - 解析CSS规则:用
cssutils库提取所有.icon-xxx:before规则的content属性值,建立类名与数字的映射关系。 - 拼接手机号:遍历HTML中的手机号元素,获取其
icon-xxx类,匹配映射关系中的数字并拼接成完整手机号。
完整代码实现
先安装依赖库:
pip install cssutils
Python代码:
from bs4 import BeautifulSoup import requests import cssutils # 目标URL与请求头 url = "https://www.justdial.com/Balasore/Readymade-Garment-Retailers/nct-10401947/page-1" headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"} # 获取页面内容 r = requests.get(url=url, headers=headers) soup = BeautifulSoup(r.content, "html.parser") # 收集页面内所有CSS代码 css_content = "" for style_tag in soup.find_all('style'): css_content += style_tag.string or "" # 解析CSS,构建类名到手机号数字的映射 css_parser = cssutils.CSSParser() stylesheet = css_parser.parseString(css_content) phone_char_map = {} for rule in stylesheet: if isinstance(rule, cssutils.css.CSSStyleRule): selector = rule.selectorText # 匹配.icon-xxx:before格式的选择器 if selector and selector.endswith(':before') and '.icon-' in selector: class_name = selector.split('.icon-')[1].split(':before')[0] content_val = rule.style.getPropertyValue('content') if content_val: # 提取content值的最后一位作为手机号数字 digit = content_val.strip('"\\\'')[-1] phone_char_map[class_name] = digit # 提取商家信息与手机号 orgs = soup.find_all('div', {'class': 'col-sm-5 col-xs-8 store-details sp-detail paddingR0'}) for org in orgs: org_name = org.find('span', {'class': 'lng_cont_name'}).get('data-cn') print(f"商家名称: {org_name}") phone_spans = org.find_all('span', {'class': 'mobilesv'}) phone_number = "" for span in phone_spans: # 获取当前span的icon类 icon_class = [cls for cls in span.get('class') if cls.startswith('icon-')][0].split('icon-')[1] if icon_class in phone_char_map: phone_number += phone_char_map[icon_class] print(f"手机号: {phone_number}\n")
关键说明
- CSS解析:
cssutils能正确处理CSS伪元素规则,避免手动正则解析的遗漏。 - 反爬提示:JustDial有反爬机制,频繁请求易触发IP封禁,建议添加请求间隔或使用代理池。
- 规则适配:若网站调整
content的编码逻辑,需同步修改数字提取的代码(比如从content中提取对应位置的字符)。
内容的提问来源于stack exchange,提问作者Partha Sarathi Dash
相关产品推荐
相关产品推荐

