以下是本人基于上课所学的的内容浓缩而成的一篇代码。
本篇承接上篇,主要介绍正则表达式与在网页解析中的应用。 2021/12/11首发于csdn,有错误和不足欢迎指出。
import re # 正则表达式
import chardet
import requests
# 正则库介绍https://blog.csdn.net/guo_qingxia/article/details/113979135?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163918918516780261966930%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163918918516780261966930&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~top_positive~default-2-113979135.pc_v2_rank_blog_default&utm_term=python%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F&spm=1018.2226.3001.4450
print(re.findall('G.D', 'GOD GOOD'))
'''先介绍一下转义与正则字符'''
# 注意是双斜杠才是一个转义,不存在\\\前两个代表\然后又和第三个合并成\,\\\在print里直接输出是\\
# 转义的目的就是让原有字符产生特殊意义
# r是让转义字符意义消失,所以r与转义是互相起反作用的
print("想输出\\t,而不是\t:", "\\t", "\n"
r"双反斜杠是转义斜杠,\t也是:", "\\\t前面有个制表符", "\n"
"r禁止双反斜杠转义:", r"\\t", "\n"
"r禁止转义:", r"\\\t")
'''----------最需要理解的部分----------'''
# 正则内有部分预定义字符会在输出输出里被解释为转义符号
# 例如"\b"在正则代表单词边界,但输出的时候会被当成退格
# 所以需要写成"\\b",或r"\b",为了防止正则被转义,可以给所有预定义字符都写成这两种形式之一
print(re.findall("\bon\b", "only on air")) # 橙色是转义字符
print(re.findall("\\bon\\b", "only on air")) # 亮黄色是正则预定义字符
print(re.findall(r"\bon\b", "only on air"))
# 其他的元字符
print(re.findall("1+1=2", "1111=2"))
print(re.findall("1\+1=2", "1+1=2"))
print(re.findall("^[^l]+", "hello")) # 不以l开头的单个字符,一个或多个
# 区分大小写,这个\A类似^用法,要放在字符串前面不能放后面,但匹配是字符串的开头,^是行开头
print(re.findall("\AHell", "Hello"))
print(re.findall("o\Z", "Helloao")) # 只匹配了结尾的o
'''正则表达式函数'''
reg1 = re.compile('to') # 即把匹配对象封装起来
reg2 = re.compile("^to")
reg3 = re.compile("to", re.I)
print(reg1.findall("To be or not to be"))
print(reg2.findall("To be or not to be"))
print(reg3.findall("To be or not to be"))
print(reg3.search("To be or not to be")) # match对象
print(reg3.match("To be or not to be")) # match对象
print(reg3.finditer("To be or not to be")) # 迭代器
'''正则表达式解析网页'''
url = 'http://www.tipdm.com/'
ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) Chrome/65.0.3325.181'}
rqg = requests.get(url, headers=ua)
# rqg.encoding = chardet.detect(rqg.content)['encoding']
# 使用findall方法查找title中的内容
# 模型字符串,搜索符合该模型的所有字符串,但最终只会返回()内的对象
title_pattern = r'<title>(.*)</title>'
# title_pattern = r'<a (.*?)>(.*?)</a>'
title_com = re.compile(title_pattern, re.M | re.S) # 将模型字符串编译成模型对象
title_find = re.findall(title_com, rqg.text) # 使用re.findall直接在网页中查找模型对象
print("标题内容:", title_find)