- HTML基础
- HTML的组成
- BeautifulSoup
- tag对象
需要熟悉HTML文件的具体格式,才能更为有效的处理HTML文件的内容
HTML基础 HTML的组成
一级标题
二级标题
三级标题
一个段落啦。一级标题、二级标题和段落,一起组成了body。
常用HTML元素
一级标题
二级标题
段落文本
描述链接的文本其他元素或文本
HTML文档的基本是由【网页头】和【网页体】组成的
网页头的内容
网页体的具体内容
head元素称为网页头
我是网页的名字
浪子回头
浪子回头
lance:
《python》
何以解忧,唯有暴富
style属性可以规定这行字的颜色,字体大小,间距,对齐方式
href属性——添加链接
class 为html元素定义一个或者多个类名
id 定义元素的唯一id
BeautifulSouppython
链接
学会使用BeautifulSoup解析和提取网页中的数据
解析熟悉的用法很简单
bs对象 = BeautifulSoup(要解析的文本,'解析器')
其中要解析的文本必须是字符串,解析器通常使用html.parser。它不是唯一的解析器,但是简单好用
import requests
from bs4 import BeautifulSoup
res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
soup = BeautifulSoup( res.text,'html.parser')
print(type(soup)) #查看soup的类型
print(soup) # 打印soup
如果需要提取数据,使用 find() 和 find_all() 方法
import requests
from bs4 import BeautifulSoup
url = 'https://localprod.pandateacher.com/python-manuscript/crawler-html/spder-men0.0.html'
res = requests.get (url)
print(res.status_code)
soup = BeautifulSoup(res.text,'html.parser')
items = soup.find_all('div') #用find_all()把所有符合要求的数据提取出来,并放在变量items里
print(type(items)) #打印items的数据类型
print(items) #打印items
find提取第一个div的内容, find_all则提取所有div的内容
我们需要找到响应的检索来提高效率
tag对象Tag.find() 和 Tag.find_all() 提取tag中的tag
Tag.text 提取Tag中的文字
Tag[‘属性名’] 输入参数:属性名,可以提取Tag总得这个属性的值
import requests
from bs4 import BeautifulSoup
res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
html = res.text
soup = BeautifulSoup( html,'html.parser')
items = soup.find_all(class_='books')
for item in items:
kind = item.find('h2')
title = item.find(class_='title')
brief = item.find(class_='info')
最后需要一个如图所示的过程



