python爬虫2---BeautifulSoup

  • BeautifulSoup是什么
  • BeautifulSoup怎么用
    • 解析数据
    • 提取数据
  • 对象的变化过程

BeautifulSoup模块
爬虫的四个步骤
0获取数据 1解析数据 2提取数据 3储存数据

学习目标
0 解析数据–BeautifulSoup
1 提取数据–BeautifulSoup

【解析数据】
我们平时使用浏览器上网,浏览器会把服务器返回来的HTML源代码翻译为我们能看懂的样子,之后我们才能在网页上做各种操作。
而在爬虫中,也要使用能读懂html的工具,才能提取到想要的数据。这就是解析数据。

【提取数据】是指把我们需要的数据从众多数据中挑选出来。

由于BeautifulSoup不是Python标准库,需要单独安装它,我们的学习系统已经安装好了。如果你是在自己的电脑上运行,需要在终端输入一行代码运行:pip install BeautifulSoup4。(Mac电脑需要输入pip3 install BeautifulSoup4)

import requests # 调用requests库
from bs4 import BeautifulSoup # 调用BeautifulSoup库
res =requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')
# 返回一个response对象,赋值给res
html=res.text
# 把res解析为字符串
soup = BeautifulSoup( html,'html.parser')
# 把网页解析为BeautifulSoup对象
items = soup.find_all(class_='books')   # 通过匹配属性class='books'提取出我们想要的元素
for item in items:                      # 遍历列表items
    kind = item.find('h2')               # 在列表中的每个元素里,匹配标签<h2>提取出数据
    title = item.find(class_='title')     #  在列表中的每个元素里,匹配属性class_='title'提取出数据
    brief = item.find(class_='info')      # 在列表中的每个元素里,匹配属性class_='info'提取出数据
    print(kind.text,'\n',title.text,'\n',title['href'],'\n',brief.text) # 打印书籍的类型、名字、链接和简介的文字 

用bs库解析数据和提取数据。
解析数据的方法是用BeautifulSoup()。
提取数据的方法是用find()与find_all()。

发布了49 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/knaha/article/details/102906925