爬虫大作业

1.选一个自己感兴趣的主题。

2.用python 编写爬虫程序,从网络上爬取相关主题的数据。

3.对爬了的数据进行文本分析,生成词云。

4.对文本分析结果进行解释说明。

5.写一篇完整的博客,描述上述实现过程、遇到的问题及解决办法、数据分析思想及结论。

6.最后提交爬取的全部数据、爬虫及数据分析源代码。

from bs4 import BeautifulSoup
import requests
import jieba
import time
import datetime

r = requests.get('https://www.qidian.com/all')
lyrics = ''
html = r.text

soup = BeautifulSoup(html, 'html.parser')

items = []
global_nav_items = soup.find('div',attrs={'class':'select-list'})

for tag in global_nav_items.find_all('a'):
    items.append(tag.string)
print(items)

# /定义一个数据存储类
class Info(object):
    #初始化值,self代表实例
    def __init__(self, title,href, img,  author,  intro):
        self.title = title
        self.img = img
        self.href = href
        self.author = author
        self.intro = intro

def save():
    now = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d')
    file_name = '起点' + now + '推荐书单'
    with open(file_name + '.txt', 'w') as file:
        file.write('#' + file_name)
        file.write('\n')
    with open(file_name + '.txt', 'a') as file:
        num = 1
        for book in book_info:
            file.write('\n\n')
            file.write('# ' + str(num) + '. ' + book.title)
            file.write('\n')
            file.write('[' + book.title + ' 封面图片](' + book.img + ')')
            file.write('\n')
            file.write('简介:')
            file.write(book.intro)
            file.write('\n')
            file.write('作者:' + book.author + '\n')
            file.write('[链接](' + book.href + ')')
            file.write('\n')
            file.write('-'*96)
            file.write('\n')
            num = num + 1
            
book_html = soup.find('ul',attrs={'class':'all-img-list cf'})
book_info = []

for ta in book_html.find_all('li'):
    cover = ta.find('div', attrs={'class':'book-img-box'})
    img = cover.find('img')['src'].strip()
    info_html = ta.find('div',attrs={'class':'book-mid-info'} )
    info_title = info_html.find('a')
    title = info_title.string.strip()
    href = info_title['href'].strip()
    author = info_html.find(attrs={'class':'name'}).string.strip()
    intro = info_html.find(attrs={'class':'intro'}).string.strip()
    book = Info(title, img, href, author, intro)
    book_info.append(book)


for book in book_info:
    print('-' * 200)
    print(book.title)
    print(book.img)
    print(book.href)
    print(book.author)
    print(book.intro)
    save()

  由于自己平时经常看小说,这一次就所学尝试着爬取了一下起点的小说页面。

       在这次操作中,我通过参考学到了许多东西,在其中我遇到了许多问题,例如:爬取时,如何对应相同标签的不同信息,后来通过标签不同的class等固定属性值。

通过词云,我们可以发现,爬取的这些小说大多是一些仙侠小说,所以不难看出我是比较喜欢看这些玄幻仙侠小说的。而通过这些小说的关键字的比重,我们可以看到这些作者写的更多的一些素材,比如:重生,穿越,凡人,仙界。如果是一个作业可以根据这些信息尝试着写一些新的素材。

文件下载:https://files.cnblogs.com/files/shadows24/%E9%BB%84%E6%B5%A9%E5%B3%B0.rar

posted @ 2018-04-30 00:49  142黄浩峰  阅读(154)  评论(0编辑  收藏  举报