python爬虫学习(五)
2019-06-20 本文已影响0人
rrrwx
(一)正则式表达
可参考http://www.runoob.com/regexp/regexp-syntax.html
import re
match = re.search(r'[1-9]\d{5}', 'BIT 200300')
# regex = re.compile(r'[1-9]\d{5}')
# match = regex.search('BIT 200300')
if match:
print(match.group(0))
for match in re.finditer(r'[1-9]\d{5}', 'BIT100081, TSU100084'):
if match:
print(match.group(0))
200300
100081
100084
Re库默认使用贪婪匹配,即输出匹配长度最长的字符串
(二)Scrapy爬虫框架
scrapy.pngScrapy 是用 Python 实现的一个为了爬取网站数据、提取结构性数据而编写的应用框架。
Scrapy 常应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中。
通常我们可以很简单的通过 Scrapy 框架实现一个爬虫,抓取指定网站的内容或图片。
scrapy是使用命令行来爬取网站数据。首先建立一个工程项目,然后在spider目录下编写爬虫代码
$ scrapy startproject spiderdemo
$ cd spiderdemo
$ scrapy genspider demo python123.io
这样就可以在spider目录下看到demo.py,然后往里面添加爬虫需求即可。
# -*- coding: utf-8 -*-
import scrapy
class DemoSpider(scrapy.Spider):
name = "demo"
#allowed_domains = ["python123.io"]
start_urls = (
'http://www.python123.io/ws/demo.html',
)
def start_request(self):
urls = (
'http://www.python123.io/ws/demo.html',
)
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
fname = response.url.split('/')[-1]
with open(fname, 'wb') as f:
f.write(response.body)
self.log('Saved file %s.' % fname)
pass
可以看到工程目录下出现一个demo.html,这样就把网页http://www.python123.io/ws/demo.html中的内容保存到了demo.html中。值得注意的是这里的yield操作。
yield可以看作是一个不断产生值的生成器,包含yield语句的函数每次产生一个值,然后函数被冻结,被唤醒后再产生一个值。
yield操作能更加节省存储空间,而且使用更灵活,很适合爬取大量网页的情况。
可参考https://www.jianshu.com/p/d09778f4e055
https://blog.csdn.net/dcrmg/article/details/78128041