用python看段子

来源:互联网 发布:mysql fetch array 编辑:程序博客网 时间:2024/05/17 08:45

周末两天时间看了一下python的语法。看完之后,总得拿个东西练练手,于是就想到了去抓取糗事百科的段子,代码如下。

#!/usr/bin/env python3# -*- coding: utf-8 -*-__author__ = 'Oliver Hu'from urllib import requestfrom bs4 import BeautifulSoupimport osurl = 'https://www.qiushibaike.com/text/'user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'class Jokes:    def __init__(self):        self.pageNo = 1        self.jokes = []    def getPage(self, pageNo):              req = request.Request(url + 'page/' + pageNo)        req.add_header('User-Agent', user_agent)        with request.urlopen(req) as html:                  html = html.read().decode('utf-8')            soup = BeautifulSoup(html, 'html.parser')            contents = soup.select('.content')            count = len(contents)            for index, text in enumerate(contents):                text = text.get_text().strip()                if text.find('查看全文') == -1:                    print(text)                    if count - 1 > index:                        command = input('\n按回车查看下一条...q退出\n')                        if command.lower() == 'q':                            break                        else:                            os.system('cls')                            continue                    else:                        command = input('\n按回车查看下一条...q退出\n')                        if command.lower() == 'q':                            break                        else:                            os.system('cls')                            self.pageNo = self.pageNo + 1                            self.getPage(str(self.pageNo))                                      else:                    print()    def run(self):        self.getPage(str(self.pageNo))print('''***********************糗事百科小爬虫描述:用另类的方式看段子作者:Oliver Hu日期:2017-09-17语言:python 3.6.2***********************''')joke = Jokes()joke.run()

运行结果如下图
这里写图片描述

代码比较简单,就不多说了,无聊的时候可以玩一玩。