环境:
靓汤4
Python2.7.5
逻辑:
'查找<li>
类为my_class
的<ul>
内的所有<li>
实例,例如:
<ul class='my_class'>
<li>thing one</li>
<li>thing two</li>
</ul>
澄清:只需在<li>
标记之间获取“文本”。
Python代码:
(下面的查找不正确,我只是把它放在上下文中)
from bs4 import BeautifulSoup, Comment
import re
# open original file
fo = open('file.php', 'r')
# convert to string
fo_string = fo.read()
# close original file
fo.close()
# create beautiful soup object from fo_string
bs_fo_string = BeautifulSoup(fo_string, "lxml")
# get rid of html comments
my_comments = bs_fo_string.findAll(text=lambda text:isinstance(text, Comment))
[my_comment.extract() for my_comment in my_comments]
my_li_list = bs_fo_string.find_all('ul', 'my_class')
print my_li_list
这个?
说明:
soup.find_all('ul', {'class': 'my_class'})
查找具有类my_class
的所有ul
标记。然后我们在那些标签中找到所有的标签,并打印标签的内容。
这是用美组3做的把戏,这台机器上没有4个。
我们的想法是先用'my_class'类搜索ul,然后在ul中查找li的findAll。
如果同一个类有额外的ul,您可能也希望在ul搜索中使用findAll,并将列表理解更改为嵌套。
相关问题 更多 >
编程相关推荐