[問題] BeautifulSoup處理超連結的問題

看板Python作者 (衝)時間14年前 (2011/05/22 12:48), 編輯推噓4(409)
留言13則, 3人參與, 最新討論串1/1
各位前輩好 我要用BeautifulSoup處理一段表格html,然後把表格橫軸和縱軸的相對應資料轉存成json 我大致已經完成,不過若表格中的內容有超連結,會碰上一些問題,例如: html=""" <td><a href="https://ceiba.ntu.edu.tw/992nihonkingendai378" target="_blank">日 本近現代史二</a>&nbsp;<br />History of Modern Japan(Ⅱ)</td> """ html = html.split() #這時候html裡的東西會被存成list;不過a、href這兩個應該要在一起的東西因為中間有 #空格的關係,分別被存在不同的位置,我猜這可能是接下來會出錯的原因 soup = BeautifulSoup(''.join(html)) print soup #<td><ahref>日本近現代史二&nbsp;<br />History of Modern Japan(Ⅱ)</ahref></td> #這時候連結會被吃掉、<a>標籤自動被改成<ahref> print soup.td.string #這時候按理說會把<td></td>之間的內容轉成string並回傳,但事實上卻回傳None 請問要怎麼解決這樣的問題呢? 另外,"&nbsp"這個html碼該怎麼處理掉? 我有大致把BeautifulSoup的Documentation瀏覽過了,但還是找不到對策..... 懇請高手指點一下,感激! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.161.124.104 ※ 編輯: BM0108 來自: 218.161.124.104 (05/22 12:48)

05/22 16:30, , 1F
直接字串取代掉 @@?
05/22 16:30, 1F


05/22 16:35, , 3F
我不太懂您的意思@@
05/22 16:35, 3F

05/24 17:31, , 4F
我是指那些特殊字元 @@
05/24 17:31, 4F

05/25 13:49, , 5F
因為<td>..</td>裡面包含其他的Tag 用soup.td.string會
05/25 13:49, 5F

05/25 13:51, , 6F
回傳None 用soup.td.contents[0]就可以抓到包含其他Tag
05/25 13:51, 6F

05/25 13:51, , 7F
的字串
05/25 13:51, 7F

05/25 13:54, , 8F
print soup.td.a.string 就會印出<a>..</a>裡的字串
05/25 13:54, 8F

05/25 14:34, , 9F
&nbsp可以用BeautifulStoneSoup來處理
05/25 14:34, 9F

05/25 14:34, , 10F
from BeautifulSoup import BeautifulStoneSoup
05/25 14:34, 10F

05/25 14:35, , 11F
soup = BeautifulStoneSoup(''.join(html),
05/25 14:35, 11F

05/25 14:35, , 12F
convertEntities=BeautifulStoneSoup.HTML_ENTITIES)
05/25 14:35, 12F

05/26 23:23, , 13F
感謝樓上!!
05/26 23:23, 13F
文章代碼(AID): #1Ds9MVUN (Python)
文章代碼(AID): #1Ds9MVUN (Python)