利用Python实现一个博客爬虫

def save_path():
s_path = ‘/home/wei/Desktop/pachong/wenjian’
if not os.path.isdir(s_path):
os.mkdir(s_path)
else:
pass
return s_path
def save_essay(blog_urls, s_path, index1=0): # 找到所有文章标题,文章内容。
for url in blog_urls:
index1 = index1+1
blog_html = requests.get(url, headers=headers)
blog_html.encoding = blog_html.apparent_encoding
soup = BeautifulSoup(blog_html.text, ‘html.parser’)
title = soup.find(‘h1’).get_text()
title = title.encode()
file = open(s_path + ‘/’+str(title)+’.txt’, ‘w’)
file.write(title)
content = soup.find_all(‘div’, {‘class’: ‘article_content’})
for p in content:
body = p.get_text()
body = body.encode()
file.write(body)
file.close()

url_all()
save_essay(essay_url(), save_path())

首先导入一些需要的工具

import requests
from bs4 import BeautifulSoup
import os
import sys

接着,下面这两行代码是为了防止报错UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 32-34: ordinal not in range(128)

reload(sys)
sys.setdefaultencoding("utf-8")

准备工作,建一个装根URL的list,header可以通过打开一个网址F12找到

url_list = []
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/58.0.3029.110 Safari/537.36'}

建立一个通过根URL找到子URL的方法

#通过打开网页可以发现CSDN博客的列表页地址为‘http://blog.csdn.net/?ref=toolbar_logo&page=’ 加一个数字,利用这样的规则,可以利用第一个函数生成200个根URL
def url_all():
    for page in range(1, 200):
        url = 'http://blog.csdn.net/?ref=toolbar_logo&page='+str(page)
        url_list.append(url)
#每一个博客列表页里,发现博客文章的地址都放在<h2>标签里,那么可以通过第二个函数返回一个放满博客文章链接的URL列表
def essay_url():  
    blog_urls = []
    for url in url_list:#对每个根URL循环
        html = requests.get(url, headers=headers)
        soup = BeautifulSoup(html.text, 'html.parser')#利用Beautiful工具解析HTML
        for h2 in soup.find_all('h2'):
            blog_url = (h2('a')[0]['href'])
            blog_urls.append(blog_url)
    return blog_urls#返回博客URL列表

获取文本内容并保存

def save_essay(blog_urls, s_path):  # 找到所有文章标题,文章内容。
    for url in blog_urls:#对每一个博客URL
        blog_html = requests.get(url, headers=headers)
        blog_html.encoding = blog_html.apparent_encoding
        soup = BeautifulSoup(blog_html.text, 'html.parser')
        title = soup.find('h1').get_text()#发现第一个<h1>中装的全是标题,则利用get_text()方法,取出其中的文本
        title = title.encode()#为了防止打印进txt文件的内容是unicode编码,加上encode()方法
        file = open(s_path + '/'+str(title)+'.txt', 'w')#以文章名创建文本文档
        file.write(title)
        content = soup.find_all('div', {'class': 'article_content'})#发现正文内容均在class=article_content的div中
        for p in content:
            body = p.get_text()
            body = body.encode()
            file.write(body)
    file.close()
发布了54 篇原创文章 · 获赞 11 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dong_W_/article/details/78796340