看板 Python 關於我們 聯絡資訊
看完了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
nio127:1.有更快的寫法 要看你的目的是針對元素還是文字內容 07/20 17:21
nio127:2跟3 你忽略了 換行。換行也是一個元素(NavigableString) 07/20 17:22