伊莉討論區

標題: Python只爬ptt內文,不要回覆(用BeautifulSoup)的方法? [打印本頁]

作者: 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
[attach]120308745[/attach]






作者: jkl99    時間: 2017-9-16 11:13 PM

只會一點點 Python 3  + google 拼拼湊湊的 不知道這樣有沒有幫助
  1. # -*- coding: utf-8 -*-
  2. from bs4 import BeautifulSoup
  3. from lxml import html
  4. import requests
  5. def main():
  6.         # 網址
  7.         pageUrl = "https://www.ptt.cc/bbs/Stock/M.1504766085.A.C9B.html"
  8.         # 取得網址內容
  9.         rs = requests.session()
  10.         res = rs.get(pageUrl, stream=True, verify=True)
  11.         soup = BeautifulSoup(res.text, "lxml")
  12.         # 取得內文
  13.         mainContent = soup.find('div', {'id':'main-content'})
  14.         # 去除不要的標籤
  15.         for s in mainContent.find_all('div', {'class':'push'}, recursive=False):
  16.                 s.decompose()
  17.         for s in mainContent.find_all('div', {'class':'article-metaline-right'}, recursive=False):
  18.                 s.decompose()
  19.         for s in mainContent.find_all('span', {'class':'f2'}, recursive=False):
  20.                 s.decompose()
  21.         for s in mainContent.find_all('div', {'class':'article-metaline'}, recursive=False):
  22.                 s.decompose()
  23.         mainContent = BeautifulSoup(mainContent.decode_contents(formatter=None), "html.parser")
  24.         print(mainContent.prettify())
  25. if __name__=='__main__':
  26.         main()
複製代碼

作者: eyny0426    時間: 2017-9-17 12:20 AM

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

感謝大大的幫忙
看您程式碼寫得簡潔有力又工整
應該是這方面的高手吧?
作者: jkl99    時間: 2017-9-18 12:54 AM

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

謝謝誇獎,但我只是拼湊,有些方法也不太懂為什麼




歡迎光臨 伊莉討論區 (http://s03.p05.eyny.com/) Powered by Discuz!