Beautiful Soup的简介:
简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。官方解释如下:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
具体可以参考官方文档
具体流程


练习:
爬取的html结构
爬取练习的步骤:
1.标题
2.列表
3.表格

1.标题
from bs4 import BeautifulSoup
with open('/Users/shixin/Downloads/15-beautifulsoup讲解/bs_test.html','r',encoding='utf-8') as fp:
html_text=fp.read()
#print(html_text)
soup=BeautifulSoup(html_text,'lxml')
#提取标题
h1_result=soup.find_all(name='h1')
h1_1=h1_result[0] #h1_result为列表取索引0
#h1_2=h1_result.pop() #返回从列表中移除的元素对象
# print(h1_1)
# print(h1_1.string.strip())
# print(h1_1.text.strip())
# print(h1_1.get_text().strip())
#print(h1_2)
#print(type(h1_result))
#print(h1_result)
tatle=h1_1.string.strip()
获取内容的三个方法:
print(h1_1.string.strip())
print(h1_1.text.strip())
print(h1_1.get_text().strip())

2.列表
#提取列表
li_result=soup.find_all('li')
#print(li_result)
li_lists=[]
for li in li_result:
li_lists.append(li.string.strip())
#print(li.string.strip())
#另外三种定位方式
div_result=soup.find_all("div",attrs={"class":"col-md-6 column"})[0] #有两个div[class="col-md-6 column"]第二个
#print(div_result)
div_result2=soup.find_all("div",class_="col-md-6 column")[0]
#print(div_result2.attrs['class'])
#从ol标签下获取
ol=div_result.ol
ol.find_all('li')
#print(ol.find_all('li'))

3.表格:
#提取表格
#table_result=soup.find_all('table',class_='table') #返回列表
table_result = soup.find('table', class_='table') #返回的是tap
#print(len(table_result),table_result)
tr_result=table_result.find_all("tr")
th_result = tr_result[0].find_all("th")
#print(len(tr_result),tr_result)
#打印标题 第一个元素
th_list=[] #存标题
table_list=[]
for th in th_result:
#print(th.get_text().strip())
th_list.append(th.get_text().strip())
table_list.append(th_list)
#抛出第一个元素打印td
tr_list=[]
for tr in tr_result[1:]:
#print(tr.get_text())
td_result=tr.find_all("td")
td_list=[]
for td in td_result:
#print(td.get_text().strip())
td_list.append(td.get_text().strip())
table_list.append(td_list)
print(th_list)
print(td_list)
for item in table_list:
print(item)
获取表格第一行在'table', class_='table'里

for tr in tr_result[1:]
print(tr.get_text())
这里循环去除第一个tr标签开始去循环,因为要获取列表第二列往后的内容


网友评论