看板 Python 關於我們 聯絡資訊
小弟目前想用lxml parse html的資料,不過卡在一個地方解不出來 下面一段是我想解的html,我要把下面的tag <p>的字串分別解出來 卡的點在Author之後,tag <strong>的部份我可以取得,但是後面就抓不出來了 不知道是哪邊處理出錯,還請各位先進指點一下 <div class="bookinfo"> <h2>C Language Teaching Manual 4th Edition (Traditional Chinese Edition)</h2> <p><strong>ISBN-13:</strong> <a href="/isbn/9789574424849">9789574424849</a></p> <p><strong>ISBN-10:</strong> <a href="/isbn/9574424847">9574424847</a></p> <p><strong>Author:</strong> HongWeiEn</p> <p><strong>Binding:</strong> Paperback</p> <p><strong>Publisher:</strong> QiBiaoChuBanGuFenYouXianGongSi</p> <p><strong>Published:</strong> December 2007</p> </div> 以下是程式碼的部份: #ISBN-13, ISBN-10, Author, Binding, Publisher, Published book_info = inforoot[0].xpath('p') for info in book_info: print info.xpath('strong')[0].text if info.xpath('a'): print info.xpath('a')[0].text else : print info[0].text -- 要感謝的人太多了,那就謝天吧 要改得程式碼太多了,那就改天吧 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.134.71.154
kilfu0701:''.join(info.xpath('./text()')) 最後一行換這樣 (?) 09/27 17:31
godman362:欸...可以欸,只是為什麼直接text會是tag <strong>的值 09/27 18:05
godman362:根據K大的解法,這樣做跟我直接取text應該會一樣啊... 09/27 18:05
godman362:我不是很清楚原因欸,不知道可否煩請K大解釋一下 09/27 18:06
kilfu0701:.text Text before the first subelement. 09/27 18:22
kilfu0701:所以你這個形況 就會抓不到東西 09/27 18:23
godman362:原來如此,這樣我懂了,感謝K大 <(__ __)> 09/27 19:11
mail6543210:要抓後面的可以用tail 09/28 17:14
godman362:請教M大,tail的用法是指:info.tail嗎? 09/30 08:10
godman362:因為我剛剛這樣一試是針對Author開始後面就都是空白的 09/30 08:10
godman362:還是我再查一下tail的用法好了,可能是我用錯了 09/30 08:10
godman362:看來是我用錯了,是info[0].tail這樣才對 09/30 08:16
godman362:感謝M大提供的另一種解法 09/30 08:16