爬取博客文章
1、去除置顶的旧文章内容:
import requests from lxml import etree url = "https://www.cnblogs.com/chingho/" r = requests.get(url) selector = etree.HTML(r.text) divs = selector.xpath('//*[@role="article"]') articles = [] for d in divs: day = d.xpath('./*[@class="dayTitle"]/a')[0] title = d.xpath('normalize-space(./*[@class="postTitle"]/a/span)') if '置顶' not in title: href = d.xpath('./*[@class="postTitle"]/a/@href')[0] article = day.text.strip() + ' ' + title.strip() + ' ' + href print(article) articles.append(article)
输出:
2、若要置顶的文章:
html_str = ''' <div class="postTitle" role="heading" aria-level="2"> <a class="postTitle2 vertical-middle pinned-post" href="https://www.cnblogs.com/chingho/archive/2010/09/05/1818373.html"> <span> <span class="pinned-post-mark">[置顶]</span> 如何管理庞大的Ajax请求? </span> </a> </div> ''' html = etree.HTML(html_str) # 置顶 result = html.xpath('//div[@class="postTitle"]/a/span/span/text()') text_0 = result[0] # 标题 result = html.xpath('//div[@class="postTitle"]/a/span/span/following-sibling::text()') # 获取当前节点之后的所有同级节点 text = result[0].strip() print(text_0 + text)
输出:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理