• Python爬虫入门教程——爬取自己的博客园博客


    互联网时代里,网络爬虫是一种高效地信息采集利器,可以快速准确地获取网上的各种数据资源。本文使用Python库requests、Beautiful Soup爬取博客园博客的相关信息,利用txt文件转存。

    基础知识:

    网络爬虫是一种高效地信息采集利器,利用它可以快速、准确地采集互联网上的各种数据资源,几乎已经成为大数据时代IT从业者的必修课。简单点说,网络爬虫就是获取网页并提取和保存信息的自动化过程,分为下列三个步骤:获取网页、提取信息、保存数据。

    1.获取网页

    使用requests发送GET请求获取网页的源代码。以获取百度为例:

    import requests
    response = requests.get('https://www.baidu.com')
    print(response.text)

    2.提取信息

    Beautiful Soup是Python的一个HTML或XML解析库,速度快,容错能力强,可以方便、高效地从网页中提取数据。基本用法:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'lxml')
    print(soup.prettify())
    print(soup.title.string)

    Beautiful Soup方法选择器:

    find_all()查询符合条件的所有元素,返回所有匹配元素组成的列表。API如下:

    find_all(name,attrs,recursive,text,**kwargs)

    find()返回第一个匹配的元素。举个栗子:

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'lxml')
    print(soup.find('div', attrs={'class': 'article-list'}))

    3.保存数据

    使用Txt文档保存,兼容性好。

    使用with as语法。在with控制块结束的时候,文件自动关闭。举个栗子:

    with open(file_name, 'a') as file_object:
        file_object.write("I love programming.
    ")
        file_object.write("I love playing basketball.
    ")

    分析页面:

    要爬取的页面是博客园“我的博客”:https://www.cnblogs.com/sgh1023/

    使用Chrome的开发者工具(快捷键F12),可以查看这个页面的源代码。

    HTML代码说白了其实就是一棵树,这棵树的根节点为html标签,head标签和body标签是它的子节点,当然有时候还会有script标签。body标签下面又会有许多的p标签、div标签、span标签、a标签等,共同构造了这棵大树。

    可以很容易看到这个页面的博文列表是一个id为mainContent的div。

     在class为postTitle的div里面可以找到链接和标题,这就是本文爬取的目标。

     

    编写代码:

    获取网页使用requests ,提取信息使用Beautiful Soup,存储使用txt就可以了。

    # coding: utf-8
    import re
    import requests
    from bs4 import BeautifulSoup
    
    def get_blog_info():
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                                 'AppleWebKit/537.36 (KHTML, like Gecko) '
                                 'Ubuntu Chromium/44.0.2403.89 '
                                 'Chrome/44.0.2403.89 '
                                 'Safari/537.36'}
        html = get_page(blog_url)
        soup = BeautifulSoup(html, 'lxml')
        article_list = soup.find('div', attrs={'id': 'mainContent'})
        article_item = article_list.find_all('div', attrs={'class': 'postTitle'})
        for ai in article_item:
            title = ai.a.text
            link = ai.a['href']
            print(title)
            print(link)
            write_to_file(title+'	')
            write_to_file(link+'
    ')
    
    
    def get_page(url):
        try:
            headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '
                                     'AppleWebKit/537.36 (KHTML, like Gecko) '
                                     'Ubuntu Chromium/44.0.2403.89 '
                                     'Chrome/44.0.2403.89 '
                                     'Safari/537.36'}
            response = requests.get(blog_url, headers=headers, timeout=10)
            return response.text
        except:
            return ""
    
    
    def write_to_file(content):
        with open('article.txt', 'a', encoding='utf-8') as f:
            f.write(content)
    
    
    if __name__ == '__main__':
        blog_url = "https://www.cnblogs.com/sgh1023/"
        get_blog_info()

    爬取结果:

    由于博主也是在攀登的路上,文中可能存在不当之处,欢迎各位多指教! 如果文章对您有用,那么请点个”推荐“,以资鼓励!
  • 相关阅读:
    yii2.0的学习之旅(一)
    elasticSearch查询(一)
    PHP--常用配置项
    php7和php5区别是什么
    做社交电商的朋友注意了!芬香的竞‌品出‌来了,小绿券,跟芬‌香几‌乎一‌模一样,但是这‌个邀请码3RIOQQ是刚刚流出的,我这里是第一手!
    为什么强烈推荐 Java 程序员使用 Google Guava 编程!
    MyBatis动态SQL(认真看看, 以后写SQL就爽多了)
    微软宣布加入 OpenJDK,打不过就改变 Java 未来!
    IntelliJ 平台 2020 年路线图
    年底了,整理了一份程序员面试必看的文章合集
  • 原文地址:https://www.cnblogs.com/sgh1023/p/10009746.html
Copyright © 2020-2023  润新知