聲明:該爬蟲只可用于提高自己學(xué)習(xí)、工作效率,請勿用于非法用途,否則后果自負
功能概述:
- 根據(jù)待爬文章url(文章id)批量保存文章到本地;
- 支持將文中圖片下載到本地指定文件夾;
- 多線程爬??;
1.爬取效果展示
本次示例爬取的鏈接地址:
https://blog.csdn.net/m0_68111267/article/details/132574687
原文效果:
爬取效果:
文件列表:
2.編寫代碼
爬蟲使用scrapy框架編寫,分布式、多線程
2.1編寫Items
class ArticleItem(scrapy.Item):
id = scrapy.Field() # ID
title = scrapy.Field()
html = scrapy.Field() # html
class ImgDownloadItem(scrapy.Item):
img_src = scrapy.Field()
img_name = scrapy.Field()
image_urls = scrapy.Field()
class LinkIdsItem(scrapy.Item):
id = scrapy.Field()
2.2添加管道
class ArticlePipeline():
def open_spider(self, spider):
if spider.name == 'csdnSpider':
data_dir = os.path.join(settings.DATA_URI)
#判斷文件夾存放的位置是否存在,不存在則新建文件夾
if not os.path.exists(data_dir):
os.makedirs(data_dir)
self.data_dir = data_dir
def close_spider(self, spider): # 在關(guān)閉一個spider的時候自動運行
pass
# if spider.name == 'csdnSpider':
# self.file.close()
def process_item(self, item, spider):
try:
if spider.name == 'csdnSpider' and item['key'] == 'article':
info = item['info']
id = info['id']
title = info['title']
html = info['html']
f = open(self.data_dir + '/{}.html'.format(title),
'w',
encoding="utf-8")
f.write(html)
f.close()
except BaseException as e:
print("Article錯誤在這里>>>>>>>>>>>>>", e, "<<<<<<<<<<<<<錯誤在這里")
return item
2.3添加配置
2.4添加解析器
...
def parse(self, response):
html = response.body
a_id = response.meta['a_id']
soup = BeautifulSoup(html, 'html.parser')
[element.extract() for element in soup('script')]
[element.extract() for element in soup.select("head style")]
[element.extract() for element in soup.select("html > link")]
# 刪除style中包含隱藏的標(biāo)簽
[
element.extract() for element in soup.find_all(
style=re.compile(r'.*display:none.*?'))
]
...
3.獲取完整源碼
項目說明文檔
愛學(xué)習(xí)的小伙伴,本次案例的完整源碼,已上傳微信公眾號“一個努力奔跑的snail”,后臺回復(fù)“csdn”即可獲取。
源碼地址:
https://pan.baidu.com/s/1uLBoygwQGTSCAjlwm13mog?pwd=****文章來源:http://www.zghlxwxcb.cn/news/detail-698825.html
提取碼: ****文章來源地址http://www.zghlxwxcb.cn/news/detail-698825.html
到了這里,關(guān)于python批量下載csdn文章的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!