正在学习scrapy框架,使用xpath + for循环遍历节点的方法抓取新闻时出现错误,只能抓取页面的最后一条新闻。请求明白的前辈给讲一下怎么为什么,该怎么改正。如下所示:
spider类如下:
# -*- coding: utf-8 -*-
import scrapy
from news.items import NewsItem
class MessageSpider(scrapy.Spider):
name = 'message'
allowed_domains = ['www.xinhuanet.com/world']
#抓取的网址,新华网国际版首页
start_urls = ['http://www.xinhuanet.com/world/']
def parse(self, response):
items = []
item = NewsItem()
for r in response.xpath('//li[@class="clearfix"]'):
#抓取标题
item['title'] = r.xpath('./h3/a/text()').extract()
#抓取简述
item['desc'] = r.xpath('string(./p/text())').extract()
#抓取时间
item['time'] = r.xpath('./div/span/text()').extract()
items.append(item)
return items
pipelines类如下:
# -*- coding: utf-8 -*-
import os
class NewsPipeline(object):
def process_item(self, item, spider):
#获取当前工作目录
base_dir = os.getcwd()
file_name = base_dir + '/message.txt'
with open(file_name, 'a', encoding='utf-8') as f:
f.write(str(item['title'])+ '\n')
f.write(str(item['desc'])+ '\n')
f.write(str(item['time'])+ '\n\n')
print(item)
return item
抓取的结果如下:
1. 打印抓取结果,显示只抓取了最后一条新闻,数了一下,抓取了34次。
2. 抓取结果写入txt中,显示写入了最后一条新闻,17次
请明白原因的前辈不吝赐教!感谢!!
item = NewsItem()
这句放到循环里面。