其实是因为反复使用命令
scrapy crawl spider -o 1.json
时候,增加的输出数据不会覆盖,而是继续往后面添加。
2.request不执行
Request(url,meta={'item':item},callback=self.parse2, dont_filter=True)
dont_filter=True让allowed_domains失效了。但是改过了还是不行。
最终结果发现改的文件和运行的文件不一样……
为什么会这样呢?我中间做了一部分实现了初始功能,就重命名了备份,然而执行命令行竟然一直在执行备份文件。
3.在使用 scrapy,pipeline 保存 json等文件时,在保存/输出中文时,会出现unicode码
import json
import codecs
class FilterWordsPipeline(object):
def __init__(self):
# self.file = open('data.json', 'wb')
self.file = codecs.open(
'scraped_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(line)
return item
def spider_closed(self, spider):
self.file.close()
ITEM_PIPELINES = {
'web.pipelines.WebPipeline': 300,
}
也就是在pipelines.py中将其改为默认utf-8打开
4.如何在解析函数之间传递值?
一种常见的情况:在parse中给item某些字段提取了值,但是另外一些值需要在parse_item中提取,这时候需要将parse中的item传到parse_item方法中处理,显然无法直接给parse_item设置而外参数。 Request对象接受一个meta参数,一个字典对象,同时Response对象有一个meta属性可以取到相应request传过来的meta。所以解决上述问题可以这样做:
def parse(self, response):
# item = ItemClass()
yield Request(url, meta={'item': item},callback=self.parse_item)
def parse_item(self, response):
item = response.meta['item']
item['field'] = value
yield item
Some Experiences Of Usin
5.错误提示URLError:<urlopen error [Errno 10051]>.这个问题我想大家都会碰到的。解决方法是在spider.py文件中加入两句话就可以:
from scrapy import optional_features
optional_features.remove('boto')
6.from scrapy.spider import BaseSpider
这句可能会报错,是因为BaseSpider是老版本的用法,应该使用新版本中的模块。在使用过程发现scrapy还是很智能的,会有相关提示应该怎样替换。正确的导入方法是:from scrapy.spiders import Spider
7.属性path
这是很多老教程的用法,现在使用会报错,应该使用xpath或selector替换
8.一直提示 No module items
后来查询资料是spiders目录中的.py文件不能和项目名同名。改个名字就行了。