1. 程式人生 > >python爬蟲四:爬取貼吧資料

python爬蟲四:爬取貼吧資料

# -*- coding: utf-8 -*-
import requests
import time
from bs4 import BeautifulSoup

import io
import sys
#sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gbk') #改變標準輸出的預設編碼
#生活大爆炸吧
'''
 # 標題&帖子連結:
    <a rel="noreferrer" href="/p/4788526595" title="我的人物設計和製作" target="_blank" class="j_th_tit ">我的人物設計和製作</a>
    
#發帖人:
    <span class="tb_icon_author " title="主題作者: 新日落" data-field="{"user_id":2137596235}"><i class="icon_author"></i><span class="frs-author-name-wrap"><a rel="noreferrer" data-field="{"un":"\u65b0\u65e5\u843d"}" class="frs-author-name j_user_card " href="/home/main/?un=%E6%96%B0%E6%97%A5%E8%90%BD&ie=utf-8&fr=frs" target="_blank">新日落</a></span><span class="icon_wrap  icon_wrap_theme1 frs_bright_icons "></span>    </span>
#發帖日期:
  <span class="pull-right is_show_create_time" title="建立時間">2016-09</span>
  
  
#回覆數量:
    <div class="col2_left j_threadlist_li_left">
<span class="threadlist_rep_num center_text" title="回覆">73</span>
    </div>
'''
#抓取網頁的通用框架,獲取頁面的內容
def getHtml(url):
    try:
        r= requests.get(url,timeout=30)
        #狀態碼不是200就發出httpError的異常
        r.raise_for_status()
        #獲取正確的編碼格式
        # r.encoding=r.apparent_encoding
        r.encoding="utf-8"
        #列印內容
        return r.text


    except:
        return "wrong!"



#分析網頁的html檔案,整理資訊,儲存問列表檔案中
def get_content(url):
    #初始化一個列表來儲存所有的帖子資訊
    contents=[]

    #獲取網頁的內容
    html=getHtml(url)

    #將網頁內容格式化利用bs4庫
    soup = BeautifulSoup(html, 'lxml')

    #獲取所有的li標籤屬性為 j_thread_list clearfix,用列表接收
    liTags = soup.find_all('li', attrs={'class': ' j_thread_list clearfix'})
    print  (len(liTags))

    #迴圈這個內容li集合
    for li in liTags:

        #將爬取到了每一條資訊。儲存到字典裡
        content={}

        #將異樣丟擲,避免無資料時,停止運
        try:
             #開始篩選資訊
             content['title']=li.find('a',attrs={"class":"j_th_tit"}).text.strip()#.strip()  翻譯為中文
             print (li.find('a',attrs={"class":"j_th_tit"}).text.strip())

             #獲取a標籤的內部屬性
             content['link'] ="http://tieba.baidu.com/"+li.find('a', attrs={"class": "j_th_tit"})["href"]
             print("http://tieba.baidu.com/"+li.find('a', attrs={"class": "j_th_tit"})["href"])


             content['author']=li.find('span',attrs={"class":'tb_icon_author '}).text.strip()
             print (li.find('span',attrs={"class":'tb_icon_author '}).text.strip())


             content['responseNum']=li.find('span',attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
             print(li.find(
                 'span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip())
             content['creatTime']=li.find('span',attrs={"class":'pull-right is_show_create_time'}).text.strip()
             print (li.find(
                'span', attrs={'class': 'pull-right is_show_create_time'}).text.strip())
             #將字典加入到列表中
             contents.append(content)


        except:
            print('出問題')



        #返回資料
    return contents


def writeTxt(content):

    #這裡不能寫成 f=open("data.txt",'a+')否則會亂碼,設定沉utf-8的格式,與getHtml(url):中的encoding一致
    f=open("data.txt",'a+',encoding='utf-8')

    for c in content:
        f.write('標題: {} \t 連結:{} \t 發帖人:{} \t 發帖時間:{} \t 回覆數量: {} \n'.format(
                c['title'], c['link'], c['author'], c['creatTime'], c['responseNum']))



url="http://tieba.baidu.com/f?ie=utf-8&kw=%E7%94%9F%E6%B4%BB%E5%A4%A7%E7%88%86%E7%82%B8&red_tag=z0177533255"
page=2


def main(url,page):

    url_list=[]
    #將所需要爬去的url放到列表中
    for i in range(0,page):
        url_list.append(url+'&pn='+str(i*50))

    for u in url_list:
        content=get_content(u)
        writeTxt(content)

if __name__=="__main__":
    main(url,page)
    get_content("http://tieba.baidu.com/f?ie=utf-8&kw=%E7%94%9F%E6%B4%BB%E5%A4%A7%E7%88%86%E7%82%B8&red_tag=z0177533255")



轉:https://zhuanlan.zhihu.com/p/26701898

每天進步一點點!