bs4库应用(一)

目标

  • 从网上爬下特定页码的网页
  • 对于爬下的页面内容进行简单的筛选分析
  • 找到每一篇帖子的 标题、发帖人、日期、楼层、以及跳转链接
  • 将结果保存到文本。
import requests
import time
from bs4 import BeautifulSoup
# 首先我们写好抓取网页的函数
def get_html(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.endcodding = r.apparent_endconding
        return r.text
    except:
        return " ERROR "

def get_content(url):
    '''
    分析贴吧的网页文件,整理信息,保存在列表变量中
    '''

    # 初始化一个列表来保存所有的帖子信息:
    comments = []
    # 首先,我们把需要爬取信息的网页下载到本地
    html = get_html(url)

    # 我们来做一锅汤
    soup = BeautifulSoup(html, 'lxml')

    # 分析网页代码找到所有具有‘ j_thread_list clearfix’属性的li标签。返回一个列表类型。
    liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})

    # 通过循环找到每个帖子里的我们需要的信息:
    for li in liTags:
        # 初始化一个字典来存储文章信息
        comment = {}
        # 这里使用一个try except 防止爬虫找不到信息从而停止运行
        try:
            # 开始筛选信息,并保存到字典中
            comment['title'] = li.find(
                'a', attrs={'class': 'j_th_tit '}).text.strip()
            comment['link'] = "http://tieba.baidu.com/" + \
                li.find('a', attrs={'class': 'j_th_tit '})['href']
            comment['name'] = li.find(
                'span', attrs={'class': 'tb_icon_author '}).text.strip()
            comment['time'] = li.find(
                'span', attrs={'class': 'pull-right is_show_create_time'}).text.strip()
            comment['replyNum'] = li.find(
                'span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
            comments.append(comment)
        except:
            print('出了点小问题')

    return comments


def Out2File(dict):
    '''
    将爬取到的文件写入到本地
    保存到当前目录的 TTBT.txt文件中。

    '''
    with open('TTBT.txt', 'a+', encoding='utf-8') as f:
        for comment in dict:
            f.write('标题: {} \t 链接:{} \t 发帖人:{} \t 发帖时间:{} \t 回复数量: {} \n'.format(
                comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))

        print('当前页面爬取完成')

def main(base_url, deep):
    url_list = []
    # 将所有需要爬去的url存入列表
    for i in range(0, deep):
        url_list.append(base_url + '&pn=' + str(50 * i))
    print('所有的网页已经下载到本地! 开始筛选信息。。。。')

    #循环写入所有的数据
    for url in url_list:
        content = get_content(url)
        Out2File(content)
    print('所有的信息都已经保存完毕!')

base_url = 'https://tieba.baidu.com/f?kw=%E5%91%BD%E8%BF%90%E5%86%A0%E4%BD%8D%E6%8C%87%E5%AE%9A&fr=index'
# 设置需要爬取的页码数量
deep = 3

if __name__ == '__main__':
    main(base_url, deep)

一个坑
with open(‘TTBT.txt’, ‘a+’) as f:
这样写可能有编码报错:UnicodeEncodeError: ‘gbk’ codec can’t encode character
改成这样:
with open(‘TTBT.txt’, ‘a+’, encoding=’utf-8’) as f:


   转载规则


《bs4库应用(一)》 刘坤胤 采用 知识共享署名 4.0 国际许可协议 进行许可。