作者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/cn.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