如何在特定的类中找到所有>?
发布时间:2020-12-20 12:22:35 所属栏目:Python 来源:网络整理
导读:环境: 美丽的汤4 Python 2.7.5 逻辑: ‘find_all’ li ul内的实例使用my_class类,例如: ul class='my_class'lithing one/lilithing two/li/ul 澄清:只需获取 li之间的“文字”即可.标签. Python代码: (下面的find_all不正确,我只是把它放在上下文中) fr
环境:
美丽的汤4 Python 2.7.5 逻辑: ‘find_all’< li> < ul>内的实例使用my_class类,例如: <ul class='my_class'> <li>thing one</li> <li>thing two</li> </ul> 澄清:只需获取< li>之间的“文字”即可.标签. Python代码: (下面的find_all不正确,我只是把它放在上下文中) 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标签. 然后,我们在这些ul标签中找到所有li标签,并打印标签的内容. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |