查看完整版本: Python只爬ptt內文,不要回覆(用BeautifulSoup)的方法?
頁: [1]

eyny0426 發表於 2017-9-16 03:46 PM

Python只爬ptt內文,不要回覆(用BeautifulSoup)的方法?

Python只爬ptt內文,不要回覆(用BeautifulSoup)的方法?


最近因為在研究股票,因此想把ptt股市版的資料爬下來
但是,遇到了無法"只爬內文"的問題
雖然有爬到其他相關的文章,卻看不懂...
誠心求教 > <"
目前我只能爬出回文和基本資訊(作者、標題、時間)
    print u'***內文***'
    print soup.find('div',id='main-content').text
    #write_down(res.text.encode('utf-8'))
    #write_down((soup.find(id='main-content').text).encode('utf-8'))
    print '---crawl_contain() Finish---'


因為eyny不能放上全文....故將完整程式碼放在Mega






...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div><div></div>

jkl99 發表於 2017-9-16 11:13 PM

只會一點點 Python 3  + google 拼拼湊湊的 不知道這樣有沒有幫助# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from lxml import html
import requests
def main():
        # 網址
        pageUrl = "https://www.ptt.cc/bbs/Stock/M.1504766085.A.C9B.html"
        # 取得網址內容
        rs = requests.session()
        res = rs.get(pageUrl, stream=True, verify=True)
        soup = BeautifulSoup(res.text, "lxml")
        # 取得內文
        mainContent = soup.find('div', {'id':'main-content'})
        # 去除不要的標籤
        for s in mainContent.find_all('div', {'class':'push'}, recursive=False):
                s.decompose()
        for s in mainContent.find_all('div', {'class':'article-metaline-right'}, recursive=False):
                s.decompose()
        for s in mainContent.find_all('span', {'class':'f2'}, recursive=False):
                s.decompose()
        for s in mainContent.find_all('div', {'class':'article-metaline'}, recursive=False):
                s.decompose()
        mainContent = BeautifulSoup(mainContent.decode_contents(formatter=None), "html.parser")
        print(mainContent.prettify())
if __name__=='__main__':
        main()...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

eyny0426 發表於 2017-9-17 12:20 AM

jkl99 發表於 2017-9-16 11:13 PM static/image/common/back.gif
只會一點點 Python 3  + google 拼拼湊湊的 不知道這樣有沒有幫助

感謝大大的幫忙
看您程式碼寫得簡潔有力又工整
應該是這方面的高手吧?

jkl99 發表於 2017-9-18 12:54 AM

eyny0426 發表於 2017-9-17 12:20 AM static/image/common/back.gif
感謝大大的幫忙
看您程式碼寫得簡潔有力又工整
應該是這方面的高手吧?

:loveliness:謝謝誇獎,但我只是拼湊,有些方法也不太懂為什麼
頁: [1]