一、python爬虫BeautSoup库简介
BeautifulSoup是将复杂HTML文档转换成一个复杂的树形结构,每个节点都是python对象。
BeautifulSoup四种对象
1、tag
2、NavigableString
3、BeautifulSoup
4、Comment
二、BeautSoup库爬取豆瓣电影
1、使用原理
from bs4 import BeautifulSoup import re file = open("./bs4使用.html","rb")#笔者已经事先在bs4使用.html文件夹里写入了指定网页的代码源 #file.write() html = file.read().decode("utf-8") bs = BeautifulSoup(html,"html.parser")#html.parser是解析器 print(bs.title) print("****") print(bs.title.string) #只打印里面的东西 即字符串
2、提取豆瓣电影指定内容
print(bs.a) print(bs.head) print(type(bs.head)) #Tag 标签及其内容:只能拿到第一个
3、文档遍历,使用正则表达式搜索
#文档遍历 print(bs.head.contents) print(bs.head.contents[1]) #文档的搜索 #字符串过滤:会查找与字符串完全匹配的内容 t_list = bs.find_all("a") #标签必须为a,才输出 #正则表达式搜索:使用search()方法来匹配内容 t_list = bs.find_all(re.compile("a")) #只要包含a这个字母,就都输出