python爬虫。实现网页贴吧的爬取,也可以修改后作为其他网页爬取

# coding=utf-8
import requests
# headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3941.4 Safari/537.36"}#模拟浏览器内核

class TiebaSpider:
    def __init__ (self,tieba_name):
        self.tieba_name = tieba_name
        self.url_temp = "http://tieba.baidu.com/f?kw="+tieba_name+"&ie=utf-8&pn={}"
        self.headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3941.4 Safari/537.36"}

    def get_url_list(self):#1.构造url列表
        url_list = []
        for i in range(100):
            url_list.append(self.url_temp.format(i*2))#爬取页码*2
        return url_list           
      
       #return [self.url_temp.format(i*2) for i in range(5)]等效前4句


    def parse_url(self,url):#发送请求,获取响应
        print(url)
        response = requests.get(url,headers=self.headers)
        return response.content.decode()

    def save_html(self,html_str,page_num):#保存HTML字符串
        file_path = "{}-第{}页.html".format(self.tieba_name,page_num)
        with open(file_path,"w",encoding="utf-8") as f:
            f.write(html_str)

    def run(self):
        url_list = self.get_url_list()
        for url in url_list:
            html_str = self.parse_url(url)
            page_num = url_list.index(url)+1
            self.save_html(html_str,page_num)



if __name__ == '__main__':
    tieba_spider = TiebaSpider("lol")
    tieba_spider.run()

你可能感兴趣的:(python)