看板 Python 關於我們 聯絡資訊
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://www.ptt.cc/bbs/Python/M.1545751765.A.6F6.html
leawei: .string吧 12/26 09:26
感謝回覆 有試過 但反而很多標題消失了 ※ 編輯: nini200 (114.33.71.129), 12/26/2018 20:29:52
s860134: 看了一下結構,兩條路,用 lxml,會殘留做括弧 12/26 23:32
看來只能用lxml 它的text()不會撈到旁邊span的數字
s860134: 第二條路 re.strip 硬幹,數字的pattern 只出現在尾端 12/26 23:33
s860134: 第二條路應該比較符合你的理想 12/26 23:33
s860134: 阿 第一條路其實沒殘存,那個括弧是標題被截斷 12/26 23:34
感謝^ ^
cody880528: 在print(title.text)前面加上title.span.decompose() 12/26 23:39
之前有試過 'NoneType' object has no attribute 'decompose' 但會報錯
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