利用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()
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值