<pre name="code" class="python"># -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 15:36:15 2015
@author: tanyouwei
"""
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://www.jb51.net" class="sister" id="link1">Elsie</a>,
<a href="http://www.jb51.net" class="sister" id="link2">Lacie</a> and
<a href="http://www.jb51.net" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.
<p class="story">...
"""
soup = BeautifulSoup(html_doc) #soup就是BeautifulSoup处理格式化后的字符串
print soup.title #得到title标签
print soup.title.name
print soup.title.string
print soup.p #得到的是文档中的第一个p标签,要想得到所有标签,得用find_all函数
print soup.a #获得第一个a标签
print soup.a['href'] #获得第一个a标签的href属性的值
print soup.a['class'] #获得第一个a标签的class属性的值
print soup.a['id'] #获得第一个a标签的class属性的值
print soup.head #一些特殊的标签,比如head标签,是可以通过soup.head得到
print soup.body.contents #获得body下的所有子孩子,以列表的形式返回结果,
#可以使用[num]的形式获得,获得标签,使用.name就可以
print soup.find_all('a') #find_all函数返回的是一个序列,可以对它进行循环,依次得到想到的东西.
print soup.find_all('p','title')
print soup.find_all('a','sister')
print soup.find_all('a',class_='sister')
print soup.find(id='link3')
print soup.get_text() #返回所有的文本
print soup.p.get_text() #返回第一个p标签的文本
'''通过css查找'''
print soup.select("p.title")
print soup.select("p.story")
'''通过属性进行查找'''
print soup.find_all("a", attrs={"class": "sister"})
print soup.find_all("a", {"class", "sister"})
'''通过文本进行查找'''
print soup.find_all(text="Elsie")
print soup.find_all(text=["Tillie", "Elsie", "Lacie"])
'''限制结果个数'''
print soup.find_all("a", limit=2)
Beautiful的用法
最新推荐文章于 2021-01-29 06:03:25 发布