历史回顾
之前个人博客网站的服务器域名等到期未续,导致部分示例中www.tenliu.com的页面失效,但不影响正常教程
正则也是爬虫中页面提取的利器,如果你愿意,完全可以仅仅使用正则进行页面提取工作。当然这样相对比较麻烦,但是正则作为页面提取的一种辅助手段,往往有意想不到的效果。
下面讲讲正则吧
正则语法
具体语法就不讲啦~,相信大家用的也不少。
这里提供一个正则表达式的速查表
http://www.tenliu.top/index.php/2018/01/17/正则表达式速查表/
python正则
python中当然有支持正则的包:re。这是python标准包,不用额外安装。
我使用正则的习惯是:
- 定义正则模板
- 文本提取
>>> import re
>>> pattern = re.compile('正则表达式',re.S)
>>> results = re.findall(pattern,"文本")
提取文章标题
之前我们用xpath,提取了页面:
http://www.tenliu.top/index.php/2018/01/09/爬虫-requests学习/
的标题。这里我们用正则来提取
>>> import requests
>>> from lxml import etree
>>> url = "http://www.tenliu.top/index.php/2018/01/09/%E7%88%AC%E8%99%AB-requests%E5%AD%A6%E4%B9%A0/"
>>> page = requests.get(url).text
>>> pattern = re.compile('entry-title">(.*?)<',re.S)
>>> results = re.findall(pattern,page)
>>> print results[0]
爬虫-requests学习
很简单不是吗。
提取无序列表
之前我们用xpath,提取了页面:
http://www.tenliu.top/index.php/2018/01/09/爬虫-requests学习/
的“历史回顾”下的几个无需列表,文本和链接是我们提取的目标,用正则同样也能办到。
>>> pattern_ul = re.compile(u'i">历史回顾(.*?)</ul',re.S)
>>> results_ul = re.findall(pattern_ul,page)
>>> ul = results_ul[0]
>>> pattern = re.compile('href="(.*?)".*?>(.*?)</a',re.S)
>>> results = re.findall(pattern,ul)
>>> for item in results:
... print item[1]
... print item[0]
...
爬虫专题大纲
http://www.tenliu.top/index.php/2017/12/28/%E7%88%AC%E8%99%AB%E4%B8%93%E9%A2%98%E5%A4%A7%E7%BA%B2/
爬虫-抓包分析
http://www.tenliu.top/index.php/2017/12/28/%E7%88%AC%E8%99%AB-%E6%8A%93%E5%8C%85%E5%88%86%E6%9E%90/
urllib、urllib2、requests概述及三者关系
http://www.tenliu.top/index.php/2017/12/28/%E7%88%AC%E8%99%AB%E3%80%81python%E5%BA%93urllib%E3%80%81urllib2%E3%80%81requests%E5%85%B3%E7%B3%BB/
爬虫-urllib学习
http://www.tenliu.top/index.php/2017/12/28/%E7%88%AC%E8%99%AB-python%E7%9A%84urllib%E5%BA%93/
爬虫-urllib2学习
http://www.tenliu.top/index.php/2018/01/02/%E7%88%AC%E8%99%AB-urllib2%E5%AD%A6%E4%B9%A0/