1.首先命令行输入: scrapy startproject newsSpider
2.在spider文件夹下,建立Spider.py文件,具体如下:
import os
import scrapy
from ..items import NewsspiderItem
class newsSpider(scrapy.Spider):
name = 'news'
allowed_domains = ['sina.com.cn']
start_urls = ['http://news.sina.com.cn/guide/']
def parse(self, response):
# 通过某节点作为根节点进行大类链接遍历
for each in response.xpath("//div[@id='tab01']/div[@data-sudaclick!='citynav']"):
# 获取大类链接和大类标题
# encode('utf-8') string编码为bytes
parentUrl = each.xpath('./h3/a/@href').extract()[0]
# parentTitle = each.xpath('./h3/a/text()').extract()[0].encode('utf-8')
parentTitle = each.xpath('./h3/a/text()').extract()[0]
# 设置大类存储路径
parentpath = './data/' + parentTitle
# parentpath = parentTitle
if not os.path.exists(parentpath): # 如果不存在就创建
os.makedirs(parentpath)
# 遍历小类链接
for other in each.xpath("./ul/li/a"):
# 获取以大类链接开头的小类链接
if other.xpath('./@href').extract()[0].startswith(parentUrl):
# 注意item的位置,不同的位置会导致不同的结果。尽量不要把item的数据在外循环和内循环里面分别获取,如必须这样做,则创建空列表添加item来解决。
item = NewsspiderItem()
subUrl = other.xpath('./@href').extract()[0] #子链接
subTitle = other.xpath('./text()').extract()[0] # 子链接标题
subpath = parentpath + '/' + subTitle # 到自连接的路径

本文介绍了如何使用Python的Scrapy框架来创建一个新闻爬虫项目。首先,通过`scrapy startproject newsSpider`命令初始化项目。接着,在spiders目录下创建名为Spider.py的文件,定义爬虫逻辑,包括数据项(items.py)和数据处理管道(Pipelines.py)。此外,为了方便运行,还在项目根目录下创建了main.py作为入口文件,免去了在命令行运行的步骤。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



