一值纱、學習課題
使用Scrapy爬取某小說網(wǎng)站的內(nèi)容
二、學習目標
1.掌握Scrapy的安裝方法
2.掌握Scrapy的基本用法
三宁否、所用到的工具
1.pycharm
2.Scrapy庫
3.re(正則)庫 (還可以用etree,xpath,bs4等)
4.Powershell
四桂敛、開始項目
(一)安裝Scrapy庫
打開cmd命令行工具,輸入以下代碼
pip install scrapy
- 拓展內(nèi)容:
調(diào)用鏡像庫
1.臨時使用
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scrapy
2.設(shè)為默認(升級 pip 到最新的版本 (>=10.0.0) 后進行配置)
pip install pip -U
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
(二)創(chuàng)建項目
1.在桌面(或別處)創(chuàng)建一個文件夾筷弦,命名為scrapy項目肋演,作為存放scrapy項目的文件夾。
2.在文件夾中按住shfit鍵+鼠標右鍵調(diào)出powershell窗口
3.輸入代碼:
scrapy startproject sgyy #sgyy為項目名稱
4.scrapy項目文件目錄下自動生成了sgyy文件夾
(三)創(chuàng)建爬蟲
1.在sgyy目錄下進入powershell
2.輸入代碼:
scrapy genspider sgyyspider purepen.com #scrapy genspider+爬蟲名+域名
#運行后在scrapy項目\sgyy\sgyy\spiders 目錄下生成了sgyyspider.py文件奸笤,這就是創(chuàng)建的爬蟲核心
(四)編寫爬蟲
在pycharm中打開sgyyspider.py文件進行編寫爬蟲
# -*- coding: utf-8 -*-
import scrapy
import re #正則
class SgyyspiderSpider(scrapy.Spider):
name = 'sgyySpider' #爬蟲名字
allowed_domains = ['purepen.com'] #網(wǎng)站
start_urls = ['http://www.purepen.com/sgyy/index.htm'] #第一次開始采集的網(wǎng)址(要爬取的網(wǎng)站)
def parse(self, response):
# 從這里以上是scrapy自動創(chuàng)建好的內(nèi)容,start_urls采集的信息返回交給了response
html = re.findall('<TD><A HREF="(.*?)">',response.text)
#.*?匹配任何你需要的信息 除了換行
#.匹配任何單個字符 除了換行符
#*數(shù)量詞 任意多個字符
#哼鬓?在數(shù)量詞后表示非貪婪模式
for i in html:
url = f'http://www.purepen.com/sgyy/{i}' #.format
# print(url)
yield scrapy.Request(url, callback=self.parseDetail)
def parseDetail (self,response):
text = re.findall('face="宋體" size="3">(.*?)</font>', response.text, flags=re.S)
title = re.findall('<font color="#000000" size="3"><br><br><b>(.*?)</b>', response.text)
if text and title:
self.save2File(title[0],text[0])
@classmethod
def save2File(cls, title, text):
with open(f'{title}.text', 'a', encoding='utf-8')as fp:
fp.write(text)
(五)運行爬蟲
在爬蟲文件目錄下打開powershell輸入以下代碼
scrapy crawl sgyySpider
(六)運行結(jié)果
在爬蟲文件夾下生成了我們想要爬取的小說內(nèi)容监右,每一章節(jié)為一個txt文件,共120個
五异希、總結(jié)
(一)關(guān)于re正則表達式
1.(.*?)匹配任何你需要的信息 除了換行
2.如果想讓匹配的信息包括換行健盒,則在re.findall()中傳入?yún)?shù):
flags=re.S
3.(.*?)加括號與不加括號的區(qū)別:
加括號是返回匹配到的數(shù)據(jù)绒瘦,不包括其他匹配值
不加括號返回匹配到的數(shù)據(jù),包括其他匹配值
例如:
<META content="《三國演義》" name=description> #《三國演義》為需要的信息
'<META content="(.*?)" name=description>' #會返回'《三國演義》'
'<META content=".*?" name=description>' #會返回<META content="《三國演義》" name=description>
4.關(guān)于正則表達式扣癣,有待進一步學習(MARK)
(二)yield的用法
挖個坑惰帽,找時間專題進行學習(MARK)
(三)@classmethod
挖個坑,找時間專題進行學習(MARK)