python scrapy爬取皇冠體育源碼下載網站數據二(scrapy使用詳細介紹)
在命令行輸入如下命令,創建一個使用scrapy框架的工程
scrapy startproject scrapyDemo
1
命令
創建好後的工程結構如下圖
scrapy工程結構
輸入如下命令,在工程目錄中創建示例代碼
PS C:\ProjectPycharm> cd scrapyDemo
PS C:\ProjectPycharm\scrapyDemo> scrapy genspider example example.com
Created spider ‘example‘ using template ‘basic‘ in module:
1
2
3
4
示例代碼
上面的工程文件說明
scrapyDemo/spiders/ 爬蟲目錄,如:創建文件,編寫爬蟲規則 scrapy.cfg 項目的配置信息,主要為Scrapy命令行工具提供一個基礎的配置信息。(真正爬蟲相關的配置信息在settings.py文件中)(一般不需要做修改) items.py 設置數據存儲模板,用於結構化數據,如:Django的Model,定義的結構可在piplines中、example.py中使用 pipelines.py 數據處理行為,如:一般結構化的數據持久化(保存到excel、保存到數據庫、下載圖片到本地等) settings.py 配置文件,如:遞歸的層數、並發數,延遲下載等
2、scrapy簡單爬蟲代碼
本示例代碼以爬取今日頭條的新聞,抓取標題和內容並保存為本地文件。
1)定義爬取的條目(item)
該條目的信息 在items.py中定義,在example.py中填充,通過pipelines.py保存到excel
items.py
import scrapy
class ScrapydemoItem(scrapy.Item):
define the fields for your item here like:
# name = scrapy.Field() title = scrapy.Field() # 新聞標題 content = scrapy.Field() # 新聞內容 pass 1 2 3 4 5 6 7 8
2)爬取信息
在example.py中編寫爬取信息代碼,首先訪問FT中文網-中國咨詢,然後遍歷新聞分類banner,然後訪問該分類,在獲取該分類下的新聞列表,然後訪問每條新聞的詳細信息頁,保存新聞標題和內容到item中
① xpath分析
財經的xpath截取為:
categoryLinks = response.xpath(‘//li[@data-section="china"]/ol[@class="nav-items"]/li[@class="nav-item"]/a/@href‘).extract()
categoryNames = response.xpath(‘//li[@data-section="china"]/ol[@class="nav-items"]/li[@class="nav-item"]/a/text()‘).extract()
1
2
xpath分析
② 爬取代碼
在發起請求函數scrapy.Request中可以傳入自定義值到meta這個變量中,可以在自定義分析函數中獲取到請求中的自定義參數
-- coding: utf-8 --
import scrapy
from scrapyDemo.items import ScrapydemoItem
headers = {
‘accept‘:‘application/json, text/javascript‘,
‘accept-encoding‘:‘gzip, deflate, br‘,
‘accept-language‘:‘zh-CN,zh;q=0.9‘,
‘content-type‘:‘application/x-www-form-urlencoded‘,
‘user-agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36‘,
‘x-requested-with‘:‘XMLHttpRequest‘
}
class ExampleSpider(scrapy.Spider):
name = ‘ExampleSpider‘
allowed_domains = [‘www.ftchinese.com‘]
start_urls = []
def start_requests(self):
yield scrapy.Request(‘http://www.ftchinese.com/channel/china.html‘,headers=headers,meta={‘baseUrl‘: ‘http://www.ftchinese.com/‘}, callback=self.parse)
def parse(self, response):
baseUrl = response.meta[‘baseUrl‘]
categoryLinks = response.xpath(‘//li[@data-section="china"]/ol[@class="nav-items"]/li[@class="nav-item"]/a/@href‘).extract()
categoryNames = response.xpath(‘//li[@data-section="china"]/ol[@class="nav-items"]/li[@class="nav-item"]/a/text()‘).extract()
i = 0
for categoryLink in categoryLinks:
# meta={‘category‘: categoryNames[i]} 用於scrapy爬取信息分散在多個頁面,
# 用於向後面的parse傳遞前面parse分析得到的內容
yield scrapy.Request(baseUrl+categoryLink,headers=headers,meta={‘category‘: categoryNames[i],‘baseUrl‘:baseUrl},
callback=self.parseTwise)
i = i+1
def parseTwise(self,response):
baseUrl = response.meta[‘baseUrl‘]
newLinks = response.xpath(‘//a[@class="item-headline-link"]/@href‘).extract()
for newLink in newLinks:
yield scrapy.Request(baseUrl+newLink,headers=headers, meta=response.meta,callback=self.parseThird)
def parseThird(self,response):
category = response.meta[‘category‘]
newTitle = response.xpath(‘//h1[@class="story-headline"]/text()‘).extract()
newContent = response.xpath(‘//h1[@class="story-body"]/text()‘).extract()
item = ScrapydemoItem()
item[‘category‘] = category
item[‘title‘] = if len(newTitle)<=0 else newTitle[0]
item[‘content‘] = ‘‘ if len(newContent)<=0 else newContent[0]
yield item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
3)保存內容
在pipelines.py中編寫保存文件代碼
import os
class ScrapydemoPipeline(object):
def process_item(self, item, spider):
basePath = "c:\ft_news\"
fileFolder = basePath + "\" + item[‘category‘]
filePath = fileFolder+"\"+item[‘title‘]+".txt"
if not os.path.exists(fileFolder): # 判斷當前路徑是否存在,沒有則創建new文件夾
os.makedirs(fileFolder)
file = open(filePath, ‘w‘)
file.write(item[‘content‘]) # 寫入內容信息
file.close()
print(filePath)
return item
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4)工程啟用功能配置
想讓 ScrapydemoPipeline起作用,我們還需要在settings.py中添加開啟pipline(開啟通道)代碼。
settings.py文件代碼
BOT_NAME = ‘scrapyDemo‘
SPIDER_MODULES = [‘scrapyDemo.spiders‘]
NEWSPIDER_MODULE = ‘scrapyDemo.spiders‘
Obey robots.txt rules
ROBOTSTXT_OBEY = False
開啟pipline
ITEM_PIPELINES = {
‘scrapyDemo.pipelines.ScrapydemoPipeline‘:300
}
設置爬取速度,一般為0.25~0.3(即250ms~300ms)間,設置的時間太短,網關防火墻會截獲連接認為是惡意訪問
DOWNLOAD_DELAY = 0.3
1
2
3
4
5
6
7
8
9
10
11
12
13
3、總結
本篇博客記錄了scrapy常用的功能,同時還在示例代碼中展示了 多級訪問共享參數的方式,即
meta中放入共享參數即可
scrapy.Request(baseUrl+categoryLink,headers=headers,
meta={‘category‘: categoryNames[i],‘baseUrl‘:baseUrl},
callback=self.parseTwise)
python scrapy爬取皇冠體育源碼下載網站數據二(scrapy使用詳細介紹)