Python爬取博客网站所有页面文章内容

更多教程请移步至:洛凉博客

求助请移步至:Python自学技术交流

前几天一直在写爬取图片的代码。XXOO网站,煎蛋网妹子图,桌酷壁纸网,最好大学排名。
想看所有代码的朋友,可以上git上拉取下。
这是仓库地址:https://github.com/YGQ8988/reptile.git
最近一直在想爬文本是不是比图片还难呢?
今天就随便访问了一个博客地址,试手了一下,起初就爬取了一篇文章,然后成功获取到了文章标题,内容。然后有尝试保存到本地。成功了。
然后又观察了下页面,每篇文章的源代码所在的位置都一样。
然后尝试了下10页数据的爬取,发现有的文章内容保存不下来,报错为编码问题,但是我代码里每次requests访问都加了编码,暂时没找到解决的办法。
最后只能简单粗暴的加了try和except过滤掉了。
抓不成功,直接过滤掉。进行下一个文章爬取。
改了下代码。文件名称优化了下。

Python爬取博客网站所有页面文章内容_第1张图片
image.png

后面改了下代码,爬取全部页面。也加了下time模块做休眠,防止访问频繁IP被封。
比较菜,IP代理访问设置还不会,scrapy框架也还不会。
最近免费领了个阿里云服务器,改完后直接丢掉服务器上运行了。

Python爬取博客网站所有页面文章内容_第2张图片
image.png

下面直接贴代码了。这次代码的注释没写很多。大家自己去尝试下。
这样就会明白每行代码的作用。

import requests
from bs4 import BeautifulSoup
import bs4
import os
from time import sleep
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'}
def url_all():
    for page in range(1,401):
        url = 'http://blog.csdn.net/?ref=toolbar_logo&page='+str(page)
        url_list.append(url)
def essay_url(): #找到所有文章地址
    blog_urls = []
    for url in url_list:
        html = requests.get(url, headers=headers)
        html.encoding = html.apparent_encoding
        soup = BeautifulSoup(html.text, 'html.parser')
        for h3 in soup.find_all('h3'):
            blog_url = (h3('a')[0]['href'])
            blog_urls.append(blog_url)
    return blog_urls
def save_path():
    s_path = 'D:/blog/'
    if  not os.path.isdir(s_path):
        os.mkdir(s_path)
    else:
        pass
    return s_path
def save_essay(blog_urls,s_path): #找到所有文章标题,文章内容。
    for url in blog_urls:
        blog_html = requests.get(url, headers=headers)
        blog_html.encoding = blog_html.apparent_encoding
        soup = BeautifulSoup(blog_html.text, 'html.parser')
        try:
            for title in soup.find('span', {'class': 'link_title'}):
                if isinstance(title, bs4.element.Tag):
                    print('-----文章标题-----:', title.text)
                    blogname = title.text
                    blogname = blogname.replace("\n",'')
                    blogname = blogname.replace("\r",'')
                    blogname = blogname.replace(" ",'')
                    try:
                        file = open(s_path + str(blogname) + '.txt', 'w')
                        file.write(str(title.text))
                        file.close()
                    except BaseException as a:
                        print(a)

            for p in soup.find('div', {'class': 'article_content'}).children:
                if isinstance(p, bs4.element.Tag):
                    try:
                        file = open(s_path + str(blogname) + '.txt', 'a')
                        file.write(p.text)
                        file.close()
                    except BaseException as f:
                        print(f)
        except BaseException as b:
            print(b)
    print('---------------所有页面遍历完成----------------')
sleep(10)
url_all()
save_essay(essay_url(),save_path())

买了三本书,最近都没看了。书上讲的基本都是内置模块。
最近发现爬虫挺好玩的,也在继续学习,研究。
希望学会框架,这样就能胜任简单的爬虫工程师了。
哈哈,是不是想的太美。

你可能感兴趣的:(Python爬取博客网站所有页面文章内容)