开始爬取
修改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文件
打开看一下
就是我保存的格式。