selenium: 爬取csdn某博客主页的原创

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时,博主的文章是在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()

爬取第一篇博客测试结果:

测试结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值