Python--正则表达式/单线程网络爬虫
2016-11-10 10:30
543 查看
正则表达式
常用符号:点号,星号,问号与括号常用方法:findall,search,sub
常用技巧:
常用符号
. :匹配任意字符,换行符\n除外* :匹配前一个字符0次或无限次
? :匹配前一个字符0次或1次
.* :贪心算法
.*? :非贪心算法
() :括号内的数据会作为结果返回
常用方法
findall:匹配所有符合规律的内容(遍历所有文本),返回包括结果的列表search:匹配并提取第一个符合规律的内容(遍历到一个即可),返回一个正则表达式的对象
sub:替换符合规律的内容,返回替换后的值
#sub的使用举例 s = '123rrrrr123' output = re.sub('123(.*?)123','123%d123'%789,s) print output 输出: 123789123
####常用技巧
import re
from re import*
from re import findall,search,sub,S
使用\d+匹配纯数字
#匹配数字 a = 'asdfasf1234567fasd555fas' b = re.findall('(\d+)',a) print b 输出:['1234567', '555']
正则表达式应用
-另需要通过 pip 安装 requests 模块,不然无法使用requests方法!#-*-coding:utf8-*- import re import requests #读取源代码文件 f = open('source.txt','r')#打开一个TXT文本 html = f.read()#将读取的文本赋给变量html f.close()#关闭文本 #匹配图片网址 pic_url = re.findall('img src="(.*?)" class="lessonimg"',html,re.S) i = 0 for each in pic_url:#打开文件操作,写文件流程 print 'now downloading:' + each pic = requests.get(each) fp = open('pic\\' + str(i) + '.jpg','wb')#将图片保存至本地目录“pic”文件夹,并添加名字与后缀 fp.write(pic.content) fp.close() i += 1
正则表达式与单线程网络爬虫应用
-自动下载的图片为程序员光棍节福利!#-*—coding:utf8-*- import requests import re #下面三行是编码转换的功能,大家现在不用关心。 import sys reload(sys) sys.setdefaultencoding("utf-8") hea = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0'} si = 0 for i in range(2180,2206): my_url = 'http://jandan.net/ooxx/page-2205#comments' url = re.sub('page-(.*?)#comments','page-%d#comments'%i,my_url) html = requests.get(url,headers = hea) html.encoding = 'utf-8' #这一行是将编码转为utf-8否则中文会显示乱码。 target = re.findall('<br /><img src="(.*?)" /></p>',html.text) for each in target: print each print 'now downloading:' + each pic = requests.get(each) fp = open('pic\\' + str(si) + '.jpg', 'wb') fp.write(pic.content) fp.close() si += 1
相关文章推荐
- Python 网络爬虫 009 (编程) 通过正则表达式来获取一个网页中的所有的URL链接,并下载这些URL链接的源代码
- python网络爬虫之正则表达式(续)
- 用python写网络爬虫-使用xpath代替正则表达式
- python3实现网络爬虫(6)--正则表达式和BeautifulSoup配合使用
- 网络爬虫(六):Python中的正则表达式教程
- Python 网络爬虫 009 (编程) 通过正则表达式来获取一个网页中的所有的URL链接,并下载这些URL链接的源代码
- Python:入门到实现网络爬虫 Day4 --正则表达式
- python之正则表达式以及网络爬虫
- 05精通Python网络爬虫——正则表达式的运用
- Python 网络爬虫-正则表达式、BeautifulSoup、lxml三种提取方法
- [Python] 网络爬虫和正则表达式学习总结
- 在学习python网络爬虫时用到的正则表达式
- 一只简单的网络爬虫(基于linux C/C++)————利用正则表达式解析页面
- python3爬虫之入门基础和正则表达式
- python实现简单爬虫以及正则表达式简述
- python3爬虫之入门和正则表达式
- python爬虫(四)--python正则表达式
- python3爬虫之入门和正则表达式
- python3爬虫之入门基础和正则表达式
- Python爬虫教程——入门七之正则表达式