一、首先回忆下html的用法
二、爬虫原理
三、BeautifulSoup—— 解析和提取网页中的数据
windows需安装:pip install BeautifulSoup4
用法:bs对象=BeautifulSoup(要解析的文本,‘解析器’)
第0个参数是要被解析的文本,它必须是字符串
第1个参数用来标识解析器,我们要用的是一个Python内置库: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
案例:爬取网页中的三本书的书名、链接、和书籍介绍
import requests
from bs4 import BeautifulSoup
#引入BS库
res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
html = res.text
soup = BeautifulSoup(html,'html.parser') #把网页解析为BeautifulSoup对象
items = soup.find_all(class_='books') #使用find_all()方法提取所有class_='books'元素,并放到变量items里。
for item in items:
kind=soup.find('h2')
title=soup.find(class_='title')
brief = item.find(class_='info')
print(kind.text,'\n',title.text,'\n',title['href'],'\n',brief.text) # 打印提取出的数据
因篇幅问题不能全部显示,请点此查看更多更全内容