初學scrapy框架遇到的坑(下)

2021-10-07 01:15:57 字數 3200 閱讀 4732

接上:

初學scrapy框架遇到的坑(上)

初學scrapy遇到的坑(中)

在前面兩個中已經爬取了部落格的標題和鏈結,在這裡繼續前面的步驟,開始爬取部落格的內容部分。

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

import scrapy

from bs4 import beautifulsoup

from

..items import blogscrapyitem

class

blogspider

(scrapy.spider)

: name =

'blog'

allowed_domains =

[''] start_urls =

['']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

return targets

修改這裡面的**。

以上是很久之前所寫。

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

import scrapy

from bs4 import beautifulsoup

from

..items import blogscrapyitem

class

blogspider

(scrapy.spider)

: name =

'blog'

#allowed_domains = ['']

start_urls =

['']def

parse

(self, response)

: content=response.text

soup=beautifulsoup(content,

'lxml'

) targets=

titles=soup.find_all(

'a',class_=

'post-item-title'

) cons=soup.find_all(

'p',class_=

'post-item-summary'

) length=

len(titles)

for i in

range

(length)

: target=blogscrapyitem(

) title=titles[i]

.text

link=titles[i]

['href'

] con=cons[i]

.text.strip(

)print

('第%s篇部落格的title為:%s'

%(i +

1, title)

)print

(% link)

print

(con)

# 變成字典

target[

"title"

]= title

target[

"link"

]= link

target[

"con"

]=con

return targets

這篇文章與上兩篇相隔太久,網頁竟然有所變動。

抓取的**與上面有所不同

修改pipelines.py**

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

# define your item pipelines here

## don't forget to add your pipeline to the item_pipelines setting

# see:

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"

] con=item[

"con"

] content=title+

'\n'

+link+

'\n'

+con

self.mytarget.write(content)

return item

執行結果

看一下本地目錄

爬取完成。

scrapy遇到的坑

1.有時候我們爬取資料跑了半天,突然報錯了,例如網路中斷,我們想繼續爬取,不需程式從頭開始爬取,可以採取下面的方案 要啟用乙個爬蟲的持久化,執行以下命令 scrapy crawl somespider s jobdir crawls somespider 1然後,你就能在任何時候安全地停止爬蟲 按c...

Linux安裝scrapy框架所遇到的坑

在進行爬蟲框架學習時,第一步需要安裝scrapy框架,但這哥們可是一點也不好安裝,所以我想把我所遇到的一些問題總結一下,希望能給遇到問題的朋友帶來一些幫助。在安裝scrapy前需要安裝scrapy所依賴的包。sudo apt get install build essential sudo apt ...

Gitee初學 遇到的坑

最好的gitee使用手冊還是官方文件 gitee官方使用手冊 以下操作在vscode中均有圖形介面作為替代,但是經常操作不當,而且操作頻率並不高,故仍選擇命令列方式 開始 每次新建乙個專案時,同時新建乙個本地倉庫和gitee雲端倉庫 每個本地倉庫對應乙個雲端倉庫 每個本地倉庫最好只存乙個專案,不然感...