初学scrapy遇到的坑(中)

开始爬取
修改blog.py中的代码。Scrapy自带了xpath和css选择器,这里使用BeautifulSoup解析爬取。

# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup#导入模块

class BlogSpider(scrapy.Spider):
    name = 'blog'
    allowed_domains = ['https://www.cnblogs.com/']
    start_urls = ['https://www.cnblogs.com/']

    def parse(self, response):
        content=response.text
        soup=BeautifulSoup(content,'lxml')
        titles=soup.find_all('a',class_='titlelnk')
        length=len(titles)
        for i in range(length):
            title=titles[i].text
            print('第%s篇博客的title为:%s'%(i+1,title))

在命令框中输入:

F:\pycharm文件\学习\blog_Scrapy\blog_Scrapy>scrapy crawl blog

得到以下内容:
在这里插入图片描述
这里我感觉一直使用命令框太不方便,而且自己设置的黑色背景,看着很不舒服,就想着能不能在pycharm中直接运行程序呢?
经过查资料,得以解决。
1.在pycharm中新建一个start.py文件,当然名字可以任意 2.在其中添加以下两行代码

from scrapy import cmdline
cmdline.execute("scrapy crawl blog".split())

试一下
在这里插入图片描述
可以,这样就不用再命令框中反复输入命令了。这里说明一下,每次运行打印的结果都不一样,这由于网站的内容时刻在变动。
把得到的数据进行封装
使用items.py中的BlogScrapyItem类
导入items.py中的BlogScrapyItem,结果 。。。报错

from blog_Scrapy.items import BlogScrapyItem

各种查之后得到解决方法:导入的有问题,引用:“在一个package中,同级使用 在父级使用 ..”
所以修改导入代码为: from ..items import BlogScrapyItem

# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
from ..items import BlogScrapyItem
class BlogSpider(scrapy.Spider):
    name = 'blog'
    allowed_domains = ['https://www.cnblogs.com/']
    start_urls = ['https://www.cnblogs.com/']

    def parse(self, response):
        content=response.text
        soup=BeautifulSoup(content,'lxml')
        targets=[]
        titles=soup.find_all('a',class_='titlelnk')
        length=len(titles)
        for i in range(length):
            target=BlogScrapyItem()
            title=titles[i].text
            link=titles[i]['href']
            print('第%s篇博客的title为:%s'%(i+1,title))
            print('链接:%s'%link)

运行结果:
在这里插入图片描述
内容过多,这里只贴出一部分。打印没问题。
变成字典

# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
from ..items import BlogScrapyItem
class BlogSpider(scrapy.Spider):
    name = 'blog'
    allowed_domains = ['https://www.cnblogs.com/']
    start_urls = ['https://www.cnblogs.com/']

    def parse(self, response):
        content=response.text
        soup=BeautifulSoup(content,'lxml')
        targets=[]
        titles=soup.find_all('a',class_='titlelnk')
        length=len(titles)
        for i in range(length):
            target=BlogScrapyItem()
            title=titles[i].text
            link=titles[i]['href']
            #变成字典
            target["title"]=title
            target["link"]=link
            targets.append(target)
        return targets

命令框输入:(因为此时已经变成字典格式,在pycharm中运行是字典格式,并不会保存为target.csv文件,所以又使用命令框)

scrapy crawl blog -o target.csv
#保存为target.csv文件

目录下会生成一个target.csv文件,打开看一下
在这里插入图片描述
scrapy存储数据一般会用到pipelines.py功能。
修改pipelines.py代码

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class BlogScrapyPipeline:
    path='F:/pycharm文件/document/target.csv'
    def __init__(self):
        self.mytarget=open(self.path,'a+',encoding='utf_8')


    def process_item(self, item, spider):
        title=item["title"]
        link=item["link"]
        content=title+'\n'+link+'\n'
        self.mytarget.write(content)
        return item

取消settings.py中以下注释
在这里插入图片描述
运行程序,在 F:/pycharm文件/document下生成了target.csv文件
打开看一下
在这里插入图片描述
就是我保存的格式。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值