基於prthon爬取濰坊學院貼吧數據

原文鏈接:https://segmentfault.com/q/1010000011571253

# -*-coding:utf-8-*-

"""
獲取百度貼吧:濰坊學院的基本內容
爬蟲線路:requests - bs4
Python版本:3.5
1. 從網上爬下特定頁碼的網頁
2. 對於爬下的頁面內容進行簡單的篩選分析
3. 找到每一篇帖子的 標題、發帖人、日期、樓層、以及跳轉鏈接
4. 將結果保存到文本
"""

import requests
import time
from bs4 import BeautifulSoup


# 抓取網頁的函數
def get_html(url):
    try:
        r = requests.get(url, timeout=30)
        # 判斷網絡連接狀態,出現錯誤時拋出異常
        r.raise_for_status()
        # r.encoding = r.apparent_encoding.
        r.encoding = 'utf-8'
        return r.text
    except:
        return '網絡連接異常'


# 分析貼吧的網頁文件,整理信息,保存在列表變量中
def get_content(url):
    # 保存所有帖子信息
    comments = []
    # 獲取網址
    html = get_html(url)

    # 熬湯
    soup = BeautifulSoup(html, 'lxml')
    # 獲取li標籤的列表
    liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})
    # 遍歷帖子中需要的信息
    for li in liTags:
        # 保存文章信息到字典
        comment = {}
        # 當爬蟲找不到信息時拋出異常
        try:
            # 保存信息到字典
            comment['title'] = li.find('a', attrs={'class': 'j_th_tit '})['title']
            comment['link'] = "http://tieba.baidu.com/" + \
                              li.find('a', attrs={'class': 'j_th_tit '})['href']
            comment['name'] = li.find('a', attrs={'class': 'frs-author-name j_user_card '}).string
            comment['time'] = li.find('span', attrs={'class': 'pull-right is_show_create_time'}).string
            comment['replyNum'] = li.find(
                'span', attrs={'class': 'threadlist_rep_num center_text'}).string
            comments.append(comment)
        except:
            print('找不到相關文章信息')
    return comments


# 將結果保存到本地
def Out2File(dict):
    # 打開文件,使用追加模式
    with open('D:\BDTB.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 = 'http://tieba.baidu.com/f?ie=utf-8&kw=%E6%BD%8D%E5%9D%8A%E5%AD%A6%E9%99%A2&fr=search'
# 設置需要爬取的頁碼數量
deep = 5272

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章