创建beautifulsoup对象
from bs4 import BeautifulSoup
html=rqg.content.decode('utf-8') #字节 解码
soup=BeautifulSoup(html,'lxml') #为什么是lxml
print(soup.prettify())
对象类型
复杂的树形结构 四种对象类型
TAG:<titile>等HTML标签+其中包含的内容
两个属性:name attributes
例子:
soup.title;soup.body.a; len(soup.find_all('a'));
tag.attrs #标签下的属性的字典列表
tag['class']
NavigableString对象:包含在tag中的文本字符串内容。该对象无法被编辑。replace_with
tag=soup.title
print(tag.string)
type(tag.string) #navigableString
tag.string.replace_with('taidikeji')
BeautifulSoup对象类型:文档的全部内容。
Comment对象类型:文档的注释部分。特殊的输出格式,prettify。特殊的navigableString。<c>(略 18分左右)
搜索特定结点并获取其中的链接以及文本
find : 返回结果
find_all : 返回列表。
搜索:name参数搜索同名的全部子节点,多种过滤器;css类名模糊匹配
soup.find_all('title')
soup.title.string
soup.find_all('ul',class_='menu') #css类名完全匹配
or
soup.find_all(id='menu') #传入关键字
print(target)
print(soup.ul.find_all('a')) #ul下所有a标签
target=soup.ul.find_all('a')
urls=[]
text=[]
for tag in target:
urls.append(tag.get('herf'))
text.append(tag.get_text())
第三章ppt p45:所有findall方法