@nemos
2017-05-06T02:01:10.000000Z
字数 2519
阅读 856
py
from bs4 import BeautifulSoupsoupobj = BeautifulSoup('htmltext', 'html.parser') #将文本转换BS对象,指定解析器betterhtml = soupobj.prettify() #转换为xhtml,优化格式
'''<html><head><title>The Dormouse's story</title></head><body><p class="title" name="dromouse"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>,<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p></body></html>'''
HTML标签加上标签内的内容即为Tag
soup.tag #可直接获得tag#第一个符合的Tag
>>> soup.titletitle>The Dormouse's story</title>>>> soup.p<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
>>> soup.head.name #标签的名字即为自身head
>>> soup.p.attrs #HTML元素属性的字典{'class': ['title'], 'name': 'dromouse'}>>> soup.p['class']>>> soup.p.attrs['class']>>> soup.p.get('class') #以上三种全部等价['title']
>>> soup.p.string #获得标签内部的文字The Dormouse's story
>>> soup.name #BeautifulSoup即是一个特殊的Tag对象[document]
特殊的NavigableString
即注释内容
类型为bs4.element.Comment
soup.tag.contents #以list形式返回tag的子节点soup.tag.children #返回list的生成器对象soup.tag.descendants#返回所有子孙节点
soup.tag.string #返回节点内容#可返回唯一子节点的内容,多个内容则为Nonesoup.tag.strings #获取多个内容soup.tag.stripped_strings#去除了空白符的字符串
soup.tag.parentsoup.head.title.string.parent.name #还是titlesoup.tag.parents
soup.tag.next_sibling #前兄弟节点soup.tag.prev_siblingsoup.tag.next_siblingssoup.tag.prev_siblings
soup.tag.next_element #获得前后节点soup.tag.previous_element#前后节点不分层次
#搜索当前tag的所有tag子节点,并判断是否符合过滤器条件find_all(name,#传字符串查找相应的tag#传正则会调用match来匹配tag#传列表将任意一匹配元素返回#传True匹配任何值#传方法以tag为参数,返回True则匹配#attrs, #可以知指定特殊的属性如attrs={'data-foo' : 'value'}recursive,#如果只想搜索直接子节点点,可指定为Falsetext, #搜索文档中的字符串内容limit, #限制返回个数**kwargs) #可过滤指定的tag属性如id='id1',href=re.compile('some')#关键字加下划线,class_='class1'
find() #类似find_all,但只返回一个节点find_parents() #找父节点find_parent()find_next_siblings() #找下一个兄弟节点find_next_sibling()find_previous_siblings()#找前一个兄弟节点find_previos_sibling()find_all_next() #找下一个节点,无层次关系find_next()find_all_previous() #同上find_previos()
#返回列表,用get_text()方法获得内容soup.select('title') #标签名查找soup.select('.class1') #类名查找soup.select('#id1') #id查找soup.select('title #id1') #组合查找soup.select('head > title') #子标签查找soup.select('a[href="http://python.org"]')#属性查找