zoukankan      html  css  js  c++  java
  • 爬取百度贴吧数据(练习Python爬虫)

    爬取百度贴吧数据(Python)

    1.总代码:

    from urllib.request import Request, urlopen
    from urllib.parse import quote
    def get_html(html):
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0"
        }
        request = Request(html, headers=headers)
        response = urlopen(request)
        return response.read().decode()
    
    
    def save_html(html,filename):
        with open(filename,'w',encoding='utf-8') as f:
            f.write(html)
    
    def main():
        content = input("请输入想要获取哪个贴吧:")
        num = int(input("请输入想要获取多少页:"))
        for i in range(num):
            url = 'https://tieba.baidu.com/f?fr=ala0&kw='+quote(content)+'&tpl={}'.format(i * 50)
            html = get_html(url)
            filename = '第'+ str(i+1) +'页.html'
            save_html(html,filename)
    
    if __name__ == '__main__':
        main()
    

    2.分步解析代码

    思路:

    1.爬取页面,需要有main方法作为入口,需要获取页面方法(get_html)和保存页面方法(save_html)

    2.在get_html方法中设定请求头(header)以达到避免页面发现爬虫痕迹;response响应读取返回页面的html代码。

    3.在save_html方法中以写的方式将爬取到的页面代码写入自定义的filename文件中

    4.在main方法中接收需要的数据,在字符串拼接的过程中注意:要哪个页面(eg:百度贴吧、python)-->然后通过quote进行文字转换成指定字符串; 添加页码(以format的形式进行接收)

  • 相关阅读:
    判断一下是星期几
    猴子分桃
    免子生免子
    字符串排序
    非关系型数据库(一)
    学习redis简介(一)
    SAVEPOINT
    *****POSTGRESQL文檔
    程序员人生之路(分析的非常透彻!)
    UpperCase for ALL Text Editors
  • 原文地址:https://www.cnblogs.com/happy-prince/p/13756005.html
Copyright © 2011-2022 走看看