目的:需要从网页上爬去一些信息
工具:Python scrapy
爬去CSDN中博客的阅读排行
第一步:
创建scrapy项目 scrapy startproject XXX
第二步:
创建爬虫 进入项目目录 执行 scrapy genspider csdn_spider csdn.net
此时的项目结构为
第三步:
编辑 csdn/item.py 定义我们需要爬取的字段
这里我们爬取 阅读排行前十名的 文章标题和阅读次数
name 为文章标题
total 为阅读数量
import scrapy class CsdnItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() total = scrapy.Field()
第四部:
编辑爬虫文件 csdn/spiders/csdn_spider.py
import scrapy from csdn.items import CsdnItem class CsdnSpiderSpider(scrapy.Spider): name = 'csdn_spider' allowed_domains = ['csdn.net'] start_urls = ['https://blog.csdn.net/wuchenlhy'] def parse(self, response): body = response.xpath('//*[@id="hotarticls"]/ul[2]/li') for value in body: title = value.xpath('./a/@title').extract()[0] total = value.xpath('./span/text()').extract()[0] print(title, total) item = CsdnItem() item['name'] = title item['total'] = total yield item
第五步:
保存我们爬取到的内容
编辑csdn/settings.py
找到这一段代码取消掉注释
# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html #ITEM_PIPELINES = { # 'csdn.pipelines.CsdnPipeline': 300, #}
变成这个样子
# Configure item pipelines # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'csdn.pipelines.CsdnPipeline': 300, }
之后编辑csdn/pipelines.py
class CsdnPipeline(object): def process_item(self, item, spider): with open('csdn.txt', 'a') as fp: fp.write('{0} {1}\n'.format(item['name'], item['total']))
爬虫代码完毕
最后一步:运行爬虫
scrapy crawl csdn_spider --nolog
抓取内容我们保存在项目根目录的 csdn.txt中