iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
1
AI & Data

爬蟲在手、資料我有 - 30 天 Scrapy 爬蟲實戰系列 第 12

【Day 11】蒐集 iT 邦幫忙的技術文章 (4/6) - 內文

今天來試著抓文章的內文吧!這邊就用昨天的文章來作為爬取目標 ,順便偷人氣

決定選擇器

直接在內文中點選「右鍵 > 檢查」打開開發人員工具,可以直接定位到內文的元素 div.markdown__style,雖然上兩層還有 div.qa-markdowndiv.markdown,但其中都只有一個子元素,所以直接定位到 div.markdown__style 就可以了。

https://ithelp.ithome.com.tw/upload/images/20190926/20107875YjiqQRQ4SA.png

import requests
from bs4 import BeautifulSoup

html_doc = requests.get('https://ithelp.ithome.com.tw/articles/10220022').text
soup = BeautifulSoup(html_doc, 'lxml')

# 先找到文章區塊
content = soup.find('div', class_='markdown__style')

print(content.text)

https://ithelp.ithome.com.tw/upload/images/20190926/20107875Zc6MWBvCeL.png

文字內容前處理

使用 content.text 取到的是 div.markdown__style 標籤下所有文字節點的內容,官方建議使用 get_text() 方法來取文字內容,可以顯示一些特殊字元(例如 \n)。

https://ithelp.ithome.com.tw/upload/images/20190926/201078754wAdHpjCmT.png

如果蒐集的資料是為了分析使用,一般不會把 \n\r 這類的空白字元存起來,可以額外傳入參數把空白字元過濾掉。

content.get_text(strip=True)

如果要對每個文字節點做額外處理,可以用 stripped_strings 這個屬性取得 generator

[text for text in content.stripped_strings]

如果要取得含 HTML 標籤的結果,可以用 .decode_contents()

content.decode_contents()

https://ithelp.ithome.com.tw/upload/images/20190926/20107875OAC9dgDaeu.png


今天的內容比較簡單,因為 iT 邦幫忙的 HTML 結構相對不複雜,明天再來抓文章其他資訊吧~


上一篇
【Day 10】蒐集 iT 邦幫忙的技術文章 (3/6) - 換頁
下一篇
【Day 12】蒐集 iT 邦幫忙的技術文章 (5/6) - 文章資訊
系列文
爬蟲在手、資料我有 - 30 天 Scrapy 爬蟲實戰33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言