Python正则表达式 - 爬虫数据提取利器

正则表达式是处理文本数据的强大工具。在爬虫开发中,正则表达式常用于从原始HTML中精确提取所需信息。

一、正则表达式简介

正则表达式使用单个字符串来描述匹配某个句法规则的字符串序列。它可以快速准确地完成文本匹配和提取任务。

二、基础语法

2.1 普通字符和元字符

import re
# 普通字符匹配自身
re.findall('hello', 'hello world')  # ['hello']
# 点号匹配任意字符
re.findall('.', 'abc')  # ['a', 'b', 'c']

2.2 字符类

# 方括号内列出字符类
re.findall('[aeiou]', 'hello')  # ['e', 'o', 'o']
re.findall('[0-9]', 'abc123')  # ['1', '2', '3']

2.3 预定义字符类

  • \d - 数字 [0-9]
  • \w - 字母数字下划线
  • \s - 空白字符
  • \D - 非数字
  • \W - 非字母数字

三、量词

# * 匹配0次或多次
re.findall('a*', 'aaabbb')  # ['aaa', '']
# + 匹配1次或多次
re.findall('a+', 'aaabbb')  # ['aaa']
# ? 匹配0次或1次
re.findall('a?', 'aaabbb')  # ['a', 'a', 'a', '']
# {n} 指定次数
re.findall('a{2}', 'aaabbb')  # ['aa']

四、常用函数

4.1 findall()返回所有匹配

re.findall(r'\d+', 'abc123def456')  # ['123', '456']

4.2 search()返回第一个匹配

result = re.search(r'\d+', 'abc123')
print(result.group())  # '123'

4.3 match()从开头匹配

re.match(r'\d+', '123abc')  # 匹配成功
re.match(r'\d+', 'abc123')  # None

4.4 sub()替换

re.sub(r'\d+', '*', 'abc123')  # 'abc*'

4.5 split()分割

re.split(r'[,]', 'a,b,c')  # ['a', 'b', 'c']

五、分组和捕获

text = '张三: 13800138000'
pattern = r'(?P.+): (?P.+)'
result = re.match(pattern, text)
print(result.group('name'))   # '张三'
print(result.group('phone'))  # '13800138000'

六、断言

6.1 正向前瞻

re.findall(r'\w+(?=:)','name:123 age:25')  # ['name', 'age']

6.2 负向前瞻

re.findall(r'\w+(?!:)','name:123')  # ['name', '123']

七、编译提高效率

pattern = re.compile(r'\d{11}')
result = pattern.findall('13800138000')  # ['13800138000']

八、实战案例

8.1 提取邮箱

pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
re.findall(pattern, 'test@example.com')  # ['test@example.com']

8.2 提取手机号

pattern = r'1[3-9]\d{9}'
re.findall(pattern, '13800138000')  # ['13800138000']

8.3 提取URL

pattern = r'https?://[\w.-]+(?:/[\w./-]*)?'
re.findall(pattern, 'https://www.example.com')  # ['https://www.example.com']

8.4 提取HTML数据

html = '

用户名: 张三

' username = re.search(r'用户名: (.+)', html).group(1) # '张三'

九、常见问题

9.1 转义问题

使用原始字符串r'...'避免转义问题。

9.2 贪婪匹配

import re
text = '
内容1
内容2
' # 贪婪 re.findall(r'
.+
', text) # 匹配所有 # 非贪婪 re.findall(r'
.+?
', text) # 分别匹配

十、总结

正则表达式是爬虫工程师必须掌握的技能。建议在实际项目中多练习。

发表回复

后才能评论