Python中的正则表达式
match 从头匹配
search 全局匹配
group 获取内容
findall 匹配全部
re.S 匹配换行符
re.I 不区分大小写
惰性匹配就是匹配文本第一次结束,后边还有一样的也不去匹配了
import re # 导入正则表达式模块
text = 'hellohellohello' # 定义字符串
r = re.compile('h.*?o',re.S|re.I) # 正则表达式
print(r.search(text).group()) # 匹配字符串,获取内容
compile 里边编写正则表达式
findall用于查找全部
.*?为惰性匹配
import re # 导入正则表达式模块
text = 'hellohellohello' # 定义字符串
r = re.compile('h.*?o',re.S|re.I) # 正则表达式
print(r.findall(text)) # 匹配全部
import requests # 导入网络请求模块
import re # 导入正则表达式模块
headers={
'Cookie':'xxx',
'User-Agent':'xxx'
} # 定制请求头
url_re = re.compile('href = "(.*?)"') # 正则表达式
url = 'https://www.baidu.com/s?wd=python' # 找到网址
html = requests.get(url,headers=headers) # get请求
html.encoding='utf-8' # 设置编码格式为'utf-8'
urls=url_re.findall(html.text) # 选取网页内容
for u in urls: # 遍历选取的网页内容
print(u) # 输出内容