lxml cssselect Parsing

半腔热情 提交于 2020-01-01 18:37:44

问题


I have a document with the following data:

<div class="ds-list">
    <b>1. </b> 
    A domesticated carnivorous mammal 
    <i>(Canis familiaris)</i> 
    related to the foxes and wolves and raised in a wide variety of breeds.
</div>

And I want to get everything within the class ds-list (without <b> and <i> tags). Currently my code is doc.cssselect('div.ds-list'), but all this picks up is the newline before the <b>. How can I get this to do what I want it to?


回答1:


Perhaps you are looking for the text_content method?:

import lxml.html as lh
content='''\
<div class="ds-list">
    <b>1. </b> 
    A domesticated carnivorous mammal 
    <i>(Canis familiaris)</i> 
    related to the foxes and wolves and raised in a wide variety of breeds.
</div>'''
doc=lh.fromstring(content)
for div in doc.cssselect('div.ds-list'):
    print(div.text_content())

yields

1.  
A domesticated carnivorous mammal 
(Canis familiaris) 
related to the foxes and wolves and raised in a wide variety of breeds.



回答2:


doc.cssselect("div.ds-list").text_content()


来源:https://stackoverflow.com/questions/4909811/lxml-cssselect-parsing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!