如何查找特定< ul>中的所有< li>班级?

问题描述:

环境:

美丽汤4

Python 2.7.5

Python 2.7.5

逻辑:

'find_all'<li>实例,该实例在<ul>内且具有my_class类,例如:

'find_all' <li> instances that are within a <ul> with a class of my_class eg:

<ul class='my_class'>
<li>thing one</li>
<li>thing two</li>
</ul>

说明:只需在<li>标记之间获取文本"即可.

Clarification: Just get the 'text' between the <li> tags.

Python代码:

(下面的find_all不正确,我只是将其放在上下文中)

(The find_all below is not correct, I am just putting it in context)

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

这吗?

>>> html = """<ul class='my_class'>
... <li>thing one</li>
... <li>thing two</li>
... </ul>"""
>>> from bs4 import BeautifulSoup as BS
>>> soup = BS(html)
>>> for ultag in soup.find_all('ul', {'class': 'my_class'}):
...     for litag in ultag.find_all('li'):
...             print litag.text
... 
thing one
thing two

说明:

soup.find_all('ul', {'class': 'my_class'})查找具有my_class类的所有ul标签.

Explanation:

soup.find_all('ul', {'class': 'my_class'}) finds all the ul tags with a class of my_class.

然后,在这些ul标签中找到所有的li标签,并打印标签的内容.

We then find all the li tags in those ul tags, and print the content of the tag.