Python 一个抓取糗百的段子的小程序

复制代码
import requests
import re
#糗事百科爬虫类
class QSBK:
    #初始化方法,定义一些变量
    def __init__(self):
        self.headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"
        }
        #存放段子的变量,每一个元素是每一页的段子们
        self.stories=[]
        #存放程序是否继续运行的变量
        self.enable =False

    def getPage(self,page):
        try:
            url = 'http://www.qiushibaike.com/hot/page/' + str(page)
            print(url)
            response = requests.get(url,headers=self.headers)
            html_content = response.content.decode('UTF-8')
            #print(html_content)
            # regex=re.compile('<div class="article block untagged mb15\s\S+" id="\S+">.*?</div>')
            regex = re.compile('<h2>(.*?)</h2>.*?<div class="content">\W+<span>(.*?)</span>', re.S)
            #regex = re.compile('<h2>', re.S)
            regex_content = re.findall(regex, html_content)
            print(regex_content)
            for i in regex_content:
                self.stories.append(i[0].replace('\n', ''),i[1].replace('\n', ''))
            return self.stories
        except Exception as e:
            print('异常:%s' % e)



js = QSBK()

for i in range(100):
    lists = js.getPage(i)

    print('============================================ 第 '+str(i)+' 页 =============================================')
    print(lists)
复制代码

如果发现不能用,那就是糗百又改规则了

 

posted @   幽冥狂_七  阅读(371)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示