作者nini200 (200妮妮)
看板Python
標題[問題] 請教爬蟲bs4如何去除標籤?
時間Tue Dec 25 23:29:20 2018
import requests
from bs4 import BeautifulSoup
import re
url = '
https://tw.appledaily.com/new/realtime'
res = requests.get(url)
soup = BeautifulSoup(res.text,'lxml')
tags = soup.find('ul',attrs={'class':'rtddd slvl'})
titles = tags.find_all('h1')
for title in titles:
print(title.text)
我爬蘋果日報標題
title.text 會將文字 <span>數字</span> 合併
但我只想要文字部分 數字不要
請問如何提取呢
感謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.179.219
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1545751765.A.6F6.html
1F:推 leawei: .string吧 12/26 09:26
感謝回覆 有試過 但反而很多標題消失了
※ 編輯: nini200 (114.33.71.129), 12/26/2018 20:29:52
2F:→ s860134: 看了一下結構,兩條路,用 lxml,會殘留做括弧 12/26 23:32
看來只能用lxml 它的text()不會撈到旁邊span的數字
3F:→ s860134: 第二條路 re.strip 硬幹,數字的pattern 只出現在尾端 12/26 23:33
4F:→ s860134: 第二條路應該比較符合你的理想 12/26 23:33
5F:→ s860134: 阿 第一條路其實沒殘存,那個括弧是標題被截斷 12/26 23:34
感謝^ ^
6F:推 cody880528: 在print(title.text)前面加上title.span.decompose() 12/26 23:39
之前有試過 'NoneType' object has no attribute 'decompose' 但會報錯
7F:推 s860134: title.font.string 其實就可以了XD 12/26 23:44
有試過 但很多標題都消失了
※ 編輯: nini200 (114.33.71.129), 12/27/2018 00:45:45
※ 編輯: nini200 (114.33.71.129), 12/27/2018 00:48:28