初试python爬虫(我爬我自己的博客)

初试python爬虫(我爬我自己的博客)

自学python有一段时间了,最近刚学了一点点正则表达式和一点点爬虫的基本知识(可能连皮毛都算不上)。我就有点迫不及待来试一试。也不知道可以爬啥东西,就决定爬我自己的博客吧,尝试着爬出我自己博客里博文的标题。


代码如下:

#导入模块
import re
from urllib.request import urlopen

def getPage(url):   #获取网页源码
    response = urlopen(url)
    return response.read().decode('utf-8')

def parsePage(html):   # 匹配正则表达式
    ret = com.finditer(html)  #获取迭代器对象
    for i in ret:
        dic = {
            "title": i.group("title"),
        }
        yield dic

def main():
    url = 'https://blog.csdn.net/weixin_46791942'   #我的博客网址
    response_html = getPage(url)   # response_html是这个网页的源码 
    ret2 = parsePage(response_html) # 生成器
    f = open("乌拉.txt", "w", encoding="utf8")
    for obj in ret2:
        print(obj)
        data = str(obj)
        f.write(data + "\n")
    f.close()

com = re.compile(    #预编译正则表达式
        '<div class=.*?>.*?<h4 class=.*?>.*?</span>(?P<title>.*?)</a>', re.S)

main()

爬出来的结果:
在这里插入图片描述
虽然这并不是什么很难的爬虫,爬出来东西也没有什么实际意义,但是这是我第一次尝试爬虫,对我来说也是一个不小的收获。在此我的python学习之路。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值