使用PyCharm編寫Scrapy爬蟲程序,爬取古詩詞網(wǎng)站
本次測(cè)試案例參考廈門大學(xué)數(shù)據(jù)庫實(shí)驗(yàn)室
鏈接: https://dblab.xmu.edu.cn/blog/3937/
在PyCharm中新建一個(gè)名稱為“scrapyProject”的工程,如下圖所示,Python解釋器就選擇我們之前已經(jīng)安裝好的
本次測(cè)試環(huán)境為
Python3.7.6
在“scrapyProject”工程底部打開Terminal窗口(如下圖所示),在命令提示符后面輸入命令“pip install scrapy”,下載Scrapy框架所需文件。
下載完成后,繼續(xù)在終端中輸入命令“scrapy startproject poemScrapy”,創(chuàng)建Scrapy爬蟲框架相關(guān)目錄和文件。創(chuàng)建完成以后的具體目錄結(jié)構(gòu)如下圖所示,這些目錄和文件都是由Scrapy框架自動(dòng)創(chuàng)建的,不需要手動(dòng)創(chuàng)建。
在Scrapy爬蟲程序目錄結(jié)構(gòu)中,各個(gè)目錄和文件的作用如下:
(1)Spiders目錄:該目錄下包含爬蟲文件,需編碼實(shí)現(xiàn)爬蟲過程;
(2)init.py:為Python模塊初始化目錄,可以什么都不寫,但是必須要有;
(3)items.py:模型文件,存放了需要爬取的字段;
(4)middlewares.py:中間件(爬蟲中間件、下載中間件),本案例中不用此文件;
(5)pipelines.py:管道文件,用于配置數(shù)據(jù)持久化,例如寫入數(shù)據(jù)庫;
(6)settings.py:爬蟲配置文件;
(7)scrapy.cfg:項(xiàng)目基礎(chǔ)設(shè)置文件,設(shè)置爬蟲啟用功能等。在本案例中不用此文件
編寫代碼文件items.py
在items.py中定義字段用于保存數(shù)據(jù),items.py的具體代碼內(nèi)容如下:
import scrapy
class PoemscrapyItem(scrapy.Item):
# 名句
sentence = scrapy.Field()
# 出處
source = scrapy.Field()
# 全文鏈接
url = scrapy.Field()
# 名句詳細(xì)信息
content = scrapy.Field()
編寫爬蟲軟件
在Terminal窗口輸入命令“cd poemScrapy”,進(jìn)入對(duì)應(yīng)的爬蟲工程中,再輸入命令“scrapy genspider poemSpider gushiwen.cn”,這時(shí),在spiders目錄下會(huì)出現(xiàn)一個(gè)新的Python文件poemSpider.py,該文件就是我們要編寫爬蟲程序的位置。
下面是poemSpider.py的具體代碼:
import scrapy
from scrapy import Request
from ..items import PoemscrapyItem
class PoemspiderSpider(scrapy.Spider):
name = 'poemSpider' # 用于區(qū)別不同的爬蟲
allowed_domains = ['gushiwen.cn'] # 允許訪問的域
start_urls = ['http://so.gushiwen.cn/mingjus/'] # 爬取的地址
def parse(self, response):
# 先獲每句名句的div
for box in response.xpath('//*[@id="html"]/body/div[2]/div[1]/div[2]/div'):
# 獲取每句名句的鏈接
url = 'https://so.gushiwen.cn' + box.xpath('.//@href').get()
# 獲取每句名句內(nèi)容
sentence = box.xpath('.//a[1]/text()').get()
# 獲取每句名句出處
source = box.xpath('.//a[2]/text()').get()
# 實(shí)例化容器
item = PoemscrapyItem()
# 將收集到的信息封裝起來
item['url'] = url
item['sentence'] = sentence
item['source'] = source
# 處理子頁
yield scrapy.Request(url=url, meta={'item': item}, callback=self.parse_detail)
# 翻頁
next = response.xpath('//a[@class="amore"]/@href').get()
if next is not None:
next_url = 'https://so.gushiwen.cn' + next
# 處理下一頁內(nèi)容
yield Request(next_url)
def parse_detail(self, response):
# 獲取名句的詳細(xì)信息
item = response.meta['item']
content_list = response.xpath('//div[@class="contson"]//text()').getall()
content = "".join(content_list).strip().replace('\n', '').replace('\u3000', '')
item['content'] = content
yield item
編寫代碼文件pipelines.py
當(dāng)我們成功獲取需要的信息后,要對(duì)信息進(jìn)行存儲(chǔ)。在Scrapy爬蟲框架中,當(dāng)item被爬蟲收集完后,將會(huì)被傳遞到pipelines?,F(xiàn)在要將爬取到的數(shù)據(jù)保存到文本文件中,可以使用的pipelines.py代碼:
import json
class PoemscrapyPipeline:
def __init__(self):
# 打開文件
self.file = open('data.txt', 'w', encoding='utf-8')
def process_item(self, item, spider):
# 讀取item中的數(shù)據(jù)
line = json.dumps(dict(item), ensure_ascii=False) + '\n'
# 寫入文件
self.file.write(line)
return item
編寫代碼文件settings.py
settings.py的具體代碼如下:
BOT_NAME = 'poemScrapy'
SPIDER_MODULES = ['poemScrapy.spiders']
NEWSPIDER_MODULE = 'poemScrapy.spiders'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4421.5 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# 設(shè)置日志打印的等級(jí)
LOG_LEVEL = 'WARNING'
ITEM_PIPELINES = {
'poemScrapy.pipelines.PoemscrapyPipeline': 1,
}
運(yùn)行程序
有兩種執(zhí)行Scrapy爬蟲的方法,第一種是在Terminal窗口中輸入命令“scrapy crawl poemSpider”,然后回車運(yùn)行,等待幾秒鐘后即可完成數(shù)據(jù)的爬取。第二種是在poemScrapy目錄下新建Python文件run.py(run.py應(yīng)與scrapy.cfg文件在同一層目錄下),并輸入下面代碼:
此處使用run.py的方式文章來源:http://www.zghlxwxcb.cn/news/detail-502582.html
from scrapy import cmdline
cmdline.execute("scrapy crawl poemSpider".split())
之后執(zhí)行代碼就可以看到data.txt爬取文本數(shù)據(jù)
同級(jí)目錄下生成的data.txt文件
爬取數(shù)據(jù)展示文章來源地址http://www.zghlxwxcb.cn/news/detail-502582.html
到了這里,關(guān)于使用PyCharm編寫Scrapy爬蟲程序,爬取古詩詞網(wǎng)站的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!