有时,博主的文章是在csdn直接发布的,没有备份草稿。博客较多时,再逐页查找,进行复制备份很麻烦。所以决定试试爬虫自动爬取备份博客草稿。
网上当然也有一些尝试。不过,自己动手丰衣足食。由于互联网知识更新较快,一些经验仅供参考。由于csdn的博客(包括其它好多类似博客)“宽松”的反爬取措施,所以较容易获取内容。
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
@author: WowlNAN
@github: https://github.com/WowlNAN
@blog: https://blog.csdn.net/qq_21264377
"""
"""
获取csdn某博客主页的原创
"""
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from htmldom import *
import re
driver=webdriver.Chrome()
driver.get('https://blog.csdn.net/qq_21264377')
time.sleep(5)
articleselements=driver.find_elements_by_class_name('article-item-box')
articles={}
for e in articleselements:
try:
html=e.get_attribute('innerHTML')
paths=['//h4//a']
innerhtml=match(paths[0], html)[0]
links=re.findall('href="([^"<>]*)"', innerhtml, re.M|re.S|re.I)
articletype=re.findall('<span[^<>]*>([^<>]*)</span>', innerhtml, re.M|re.S|re.I)[0]
# 获取csdn博主原创文章
if articletype.strip()!='原创':
continue
titles=re.findall('</span>([^<>]*)</a>', innerhtml, re.M|re.S|re.I)
title=titles[0]
title=title.replace('\n','')
title=title.replace(' ','')
articles[title]=links[0]
except:
pass
keys=articles.keys()
print(keys)
# test
for key in keys:
link=articles.get(key)
driver.get(link)
time.sleep(5)
articletitle=driver.find_element_by_id('articleContentId').text
print('[title]',articletitle, '[/title]')
articlecontent=driver.find_element_by_id('content_views').text
print('[content]',articlecontent, '[/content]')
break
#没有事件关闭
driver.close()
爬取第一篇博客测试结果:

本文介绍了如何使用selenium爬虫自动化备份在csdn上发布的博客文章。由于csdn的反爬策略相对宽松,作者通过实践成功地爬取了博客内容,以解决逐页查找并复制备份的困扰。


被折叠的 条评论
为什么被折叠?



