文章旨在以小实例引导初学者理清这个号称写爬虫就如做填空题的scrapy爬虫框架的空该怎么填,比喻不当之处,欢迎指正!
一、理清框架各个模块的脉络关系
一个完整的项目设计四个python文件的编写,分别是items.py、wuhanSpider.py(scrapy genspider wuHanSpider jycinema.com后生成,非系统自带)、settings.py、pipelines.py
四个文件对应2个HOW、1个what、1个who,即是
items-->how :定义要爬取哪些项目(取个要爬取的内容的名字)
wuhanSpider.py->HOW :阐述怎么爬取,即怎么从html代码中取数据
settings-->who:定义由谁保存经处理后的爬取的内容,一般是由pipelines模块中的一个类
pipelines->HOW:怎样去保存爬取到的内容,是导出到txt文件呀?还是数据库呀?等等
二、具体四个文件要写哪些代码:
1、items.py
class Scrapy0Item(scrapy.Item): # define the fields for your item here like: moivename = scrapy.Field() #(只要起个名字作为你爬取项目范围)
2、wuhanSpider.py
from scrapy0.items import Scrapy0Item #导入前面items模块中定义的类Scrapy0Item
def parse(self, response): subSelector=response.xpath('//div [@class="film-header"]') #找到爬取信息落点大概范围 items = [] for sub in subSelector: item = Scrapy0Item() item['moivename']=sub.xpath('./a/h3/text()').extract() #在范围中取出具体目标元素 items.append(item) return items
3、settings.py
ITEM_PIPELINE={'scrapy0.pipelines.Scrapy0Pipeline':300} #告诉 Scrapy最终的结果由scrapy0模块的pipelines模块的Scrapy0Pipeline类来处理4、pipelines
这里以保存到.txt文件为例
import time class Scrapy0Pipeline(object): def process_item(self, item, spider): now = time.strftime('%Y-%m-%d',time.localtime()) fileName = 'wuhan'+ now +'.txt' with open(fileName,'a') as fp: fp.write(item['moiveName'][0].encode('utf8')+'\n\n') return item
三、最后执行
scrapy crawl wuHanSpider(项目名)
生成结果.txt文件
四、总结几种请求网页模块函数用法(urllib2和requests)
五,反反爬虫方法
1、带用户登录的post方法
2、带cookie信息的爬取
3、带自定义的请求头部的爬取
在settings加入
USER_AGENT='Mozilla/5.0(Windows NT 6.1;WOW64) AppleWeKit/537.36(KHTML,like Gecko)'