直接上代码,注释也写了
from bs4 import BeautifulSoup
#2016.10.20 Python爬虫之解析HTML
# 摘要
# 创建对象,DOM树
# 搜索节点,访问节点 - 两种方法
# 名称,属性,文字,(节点名称,节点属性,节点文本内容)
# 创建对象
soup = BeautifulSoup(
html_doc, # 文档字符串
'html.parser', # 解析器
from_encoding = 'utf-8' # 文档编码
)
# 搜索节点
soup.find_all('a') # 所有a标签
soup.find_all('a',href='#') #也可用正则表达式
soup.find_all('div',class_='xxx',string='hahaha') # 类名为xxx而且文本内容为hahaha的div
# 访问节点信息
# <a href='#'>hahaha</a>
node.name
node['href']
node.get_text() # a链接文字