python(爬虫基础贴吧)

 

    from urllib import request, parse, error
    import json
    import time
    import os
    class post_bar():
        def creeper(self, name, page, path):
            base_url = 'https://tieba.baidu.com/f?kw={}&ie=utf-8&pn={}'
            head = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
            }
            try:
                path1 = os.path.join(path,name)  
                if not os.path.exists(path1):  
                    os.mkdir(path1)    # 创建文件夹
                for i in range(page):
                    i = i * 50        # 贴吧每页帖子数量为50
                    name1 = parse.quote(name)    # 将中文转码
                    base_url1 = base_url.format(name1, i)  
                    response = request.Request(base_url1, headers=head)
                    response = request.urlopen(response)
                    response1 = response.read().decode("utf-8")
                     
                    print(path1)
                    with open(path1 + "//" +name + str(i) + '.html', 'w',encoding="utf-8") as e:
                            e.write(response1)       # 将获取到的页面写入路径中
            except error.HTTPError as e:
                    print(e.code)        # 获取报错代码
            except error.URLError as e:
                    print(e.reason)      # 获取报错原因
    file = os.getcwd()[0:-5]             # 获取当前路径
    tieba = post_bar()                   # 实例化对象
    tieba.creeper(名字, 页数, 路径)      # 调用函数

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值