[問題] BeautifulSoup的觀念問題?

看板Python作者 (HIHIHI)時間16年前 (2009/07/15 01:54), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串1/2 (看更多)
看完了BeautifulSoup的文檔,也可理解裡面的例子 但自己要用時,出現的結果跟預期的不太一樣,我可能是哪些地方有誤解, 盼有能者能幫我開悟一下 html= """ <table style="BORDER-COLLAPSE: collapse" width="100%" border="1"> <tbody> <tr> <td valign="center" align="left" width="125" bgcolor="#f2f3f1" height="25"> 不選我 </td> <td valign="center" align="left" width="547" height="25"> <p style="MARGIN-LEFT: 10px"> 選我 </p> </td> </tr> <tr> </tr> </tbody> </table> """ soup = BeautifulSoup(html) table = soup.table Q1: print table.tr.nextSibling.previous.string ==> 結果出現 "選我" 這個符合我的預期,但用這樣子覺得很遜,是找不到方法下才用的 Q2: print table.tr.td.nextSibling.name ==>結果出現 'NavigableString' object has no attribute 'name' 原本我是這樣子使用,但結果跟我預期完全不同,為什麼這個無法選到呢? 疑惑? NavigableString不是應該是標籤內text的部份嗎? Q3: print table.tr.contents[3].p.string ==> 結果出現 "選我" 我原本預期應該是 table.tr.contents[1].p.string , 為什麼又與我預期的不同? 以上問題,百思不解 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.124.185.18

07/20 17:21, , 1F
1.有更快的寫法 要看你的目的是針對元素還是文字內容
07/20 17:21, 1F

07/20 17:22, , 2F
2跟3 你忽略了 換行。換行也是一個元素(NavigableString)
07/20 17:22, 2F
文章代碼(AID): #1ANJRbPs (Python)
討論串 (同標題文章)
文章代碼(AID): #1ANJRbPs (Python)