当前位置: 移动技术网 > IT编程>脚本编程>Python > 初试python爬虫(我爬我自己的博客)

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

2020年07月14日  | 移动技术网IT编程  | 我要评论

初试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学习之路。

本文地址:https://blog.csdn.net/weixin_46791942/article/details/107318773

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网