当前位置: 移动技术网 > IT编程>脚本编程>Python > Python爬虫入门教程——爬取自己的博客园博客

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

2018年11月24日  | 移动技术网IT编程  | 我要评论

情书第二季全集,杨殿钟是谁的秘书,邓家齐

互联网时代里,网络爬虫是一种高效地信息采集利器,可以快速准确地获取网上的各种数据资源。本文使用python库requests、beautiful soup爬取csdn博客的相关信息,利用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.\n")
    file_object.write("i love playing basketball.\n")

分析页面:

要爬取的页面是博客园“我的博客”:。

使用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+'\t')
        write_to_file(link+'\n')


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()

爬取结果:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网