python简单实现获取优快云博客文章相关信息

本文介绍了一个使用Python和BeautifulSoup实现的简单爬虫,用于抓取优快云博客上的文章链接、标题、类型及简介。该爬虫在Windows 7 x64环境下运行,针对Python 3.7版本进行编写。通过定义Spider类,实现了从指定页面范围内的优快云博客抓取数据,并将结果输出到HTML文件中。

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

需求

获取博客文章的链接、标题、类型、简介内容。

环境

Win7 x64,Python 3.7

实现 

# coding: UTF-8
from bs4 import BeautifulSoup
import urllib.request as urlrequest
import re
 
class Spider(object):
    def __init__(self):
        self.pages=[]
        self.datas=[]
        self.root="https://blog.youkuaiyun.com/wingrez"
        
    def claw(self, startpage, endpage):
        for i in range(startpage, endpage+1):
            self.pages.append(self.root+"/article/list/%d?" % i )
        for url in self.pages:
            self.getDatas(url)
            
    def download(self, url): # 下载当前网页内容
        if url is None:
            print("链接为空!")
            return None
        response=urlrequest.urlopen(url)
        if response.getcode()!=200:
            print("访问失败!")
            return None
        return response.read()
        
    def getDatas(self, url): # 获取当前页所有文章信息
        html_cont=self.download(url)
        soup=BeautifulSoup(html_cont, 'html.parser', from_encoding='UTF-8')
        articles=soup.find_all('div', class_='article-item-box csdn-tracking-statistics')
        for article in articles:
            data={}
            tag_a=article.find('h4').find('a')
            data['url']=tag_a['href']
            tag_span=tag_a.find('span')
            data['type']=tag_span.string
            data['title']=tag_span.next_element.next_element
            data['summary']=article.find('p').find('a').string
            self.datas.append(data)
            
    def output(self): # 输出数据
        fout=open('output.html','w',encoding="UTF-8")
        fout.write("<html>")
        fout.write("<body>")
        fout.write("<table>")
        for data in self.datas:
            fout.write("<tr>")
            fout.write("<td>%s</td>" % data['type'])
            fout.write("<td>%s</td>" % data['url'])
            fout.write("<td>%s</td>" % data['title'])
            fout.write("<td>%s</td>" % data['summary'])
            fout.write("</tr>")
        fout.write("</table>")
        fout.write("</body>")
        fout.write("</html>")
        fout.close()
    
if __name__=="__main__":
    spider=Spider()
    spider.claw(1,12)
    spider.output()

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wingrez

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值