正则表达式解析网页
正则表达式就是对字符串进行操作的逻辑公式,相当于‘过滤’这个字符串。
可以把网页源码变成字符串,再用正则表达式对其进行提取。
正则表达式的几个方法:
- re.match方法:
re.match代表从字符串起始进行匹配,无法匹配则为None。
re.match的使用方法是:re.match(pattern,string,flags=0),pattern是正则表达式,string是字符串。
import re
test=re.match('www','www.baidu.com')
print('result:',test)
print('begin and end tuple:',test.span()) ##匹配结果的开始位置和结束位置
print('begin:',test.start())
print('end:',test.end())
修改正则表达式:
import re
pattern ='Cats are smarter than dogs'
test=re.match(r'(.*)are(.*?)dogs',pattern) ##r为纯字符,防止反斜杠转译
print('the whole sentence:',test.group(0))
print('the first result:',test.group(1))
print('the second result:',test.group(2))
print('a tuple for result:',test.group()) 匹配cats和smarter than
- re.search方法:
re.match只从字符串开始进行匹配,re.search扫描整个字符串并返回第一个匹配。
import re
link='www.baidu.com'
print(re.match('baidu',link))
print(re.search('baidu',link))
两者的区别:match开头没有直接返回none,而search从头扫描到尾。
- re.findall方法:
可以找到所有的匹配。
import re
link='www.baidu.com www.baidu.com'
print(re.match('www',link))
print(re.search('www',link))
print(re.findall('www',link))
match和search都只返回了一个www,但是findall找到了所有。
实践
现在尝试用正则表达式爬去博客日期:
import re
import requests
link='https://blog.csdn.net/even160941'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'}
r=requests.get(link,headers=headers)
html=r.text ##获取网页源码
date=re.findall('<span class="date">(.*?)</span>',html)
for each in date:
print(each)
制作翻页功能:
import re
import requests
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'}
for i in range(1,3):
link='https://blog.csdn.net/even160941/article/list/'+str(i)+'?'
r=requests.get(link,headers=headers)
html=r.text
date=re.findall('<span class="date">(.*?)</span>',html)
for each in date:
print(each)
注:本博客参考https://blog.csdn.net/weixin_42183408/article/details/87451092