Python—爬取贴吧前三页数据

import requests
class TiebaSpider:

def __init__(self,tieba_name):
    self.tieba_name = tieba_name
    self.url_temp = "https://tieba.baidu.com/f?kw="+tieba_name+"&ie=utf-8&pn={}"
    self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}


def get_url_list(self):#1.url列表
    url_list = [self.url_temp.format(i*50) for i in range(3)]
    return url_list


def parse_url(self,url):#发送请求,拿到响应html字符串
    print("现在正在请求:{}".format(url))
    response = requests.get(url,headers=self.headers)
    return response.content.decode()


def save_html_str(self,html_str,page_num):
    file_path = "{}_第{}页.html".format(self.tieba_name,page_num)
    with open(file_path,"w",encoding="utf-8") as f:
        f.write(html_str)
    print("保存成功")


def run(self):
    #1.url列表
    url_list = self.get_url_list()
    #2.遍历,发送请求,拿到响应
    for url in url_list:
        html_str = self.parse_url(url)
        #3.保存
        page_num = url_list.index(url)+1
        self.save_html_str(html_str,page_num)

if name == ‘main’:
tieba_spider = TiebaSpider(“python”)
tieba_spider.run()

结果:
在这里插入图片描述

你可能感兴趣的:(Python—爬取贴吧前三页数据)