内容采集(Python爬虫爬取学校官网新闻标题与库的一些功能介绍)
优采云 发布时间: 2021-11-18 16:03内容采集(Python爬虫爬取学校官网新闻标题与库的一些功能介绍)
Python爬虫爬取学校官网新闻标题和链接
一、前言
⭐本文根据学校的课程内容进行总结,爬取的数据仅供学习使用,请勿用于其他用途
基础知识:二、扩展库简介
接下来Pola将简单介绍一下在爬取数据的过程中用到的urllib库和Beautiful库的一些功能。
01 urllib 库
urllib 库是python内置的HTTP请求库,包括以下模块:
(1)urllib.request.urlopen()
urlopen返回的响应对象为http.client.HTTPResponse类型,主要包括read()、readinfo()、getheader(name)、getheaders()、fileno()等方法。我们需要使用的是 read() 方法,如下:
# 导入 urllib.request 模块
import urllib.request
# 解析我们给定的 url: https://www.hist.edu.cn/index/sy/kyyw.htm
# 即读取给定 url 的 html 代码 --> 输入 url, 输出 html
response = urllib.request.urlopen('https://www.hist.edu.cn/index/sy/kyyw.htm')
# 打印我们获取到的数据,并以 utf-8 形式进行解码
# 需要注意:修改 pycharm 的编码方式为 utf8, 否则会报错
print(response.read().decode('utf-8'))
⭐不会修改pycharm的编码方式,请参考:Pycharm-修改编码方式为'utf8'
代码输出结果如下(长度太长,只有一部分):
02 BeautifulSoup 库
BeautifulSoup 是 Python 的第三方库,可用于解析 html 数据。我们的主要功能是从网页中抓取数据:
(1)BeautifulSoup()
BeautifulSoup 将复杂的 HTML 文档转换为复杂的树结构,其中每个节点都是一个 Python 对象。所有对象可以分为4类:
我们可以使用 BeautifulSoup() 来转换上面读取的 html 文档,如下:
import urllib.request
from bs4 import BeautifulSoup
# 读取给定 url 的 html 代码
response = urllib.request.urlopen('https://www.hist.edu.cn/index/sy/kyyw.htm')
content = response.read().decode('utf-8')
# 转换读取到的 html 文档
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
(2)find_all()
find_all() 搜索文档树,搜索当前标签的所有标签子节点,判断是否满足过滤条件。返回值类型为bs4.element.ResultSet,即返回的是多个对象的集合,可以通过for循环遍历。完整的语法如下:
find_all(名称,属性,递归,字符串,**kwargs)
参数含义如下:
上面我们已经转换了html文档,接下来我们使用find_all()来获取我们想要的数据,但是在此之前,我们需要知道我们搜索数据的条件是什么?这需要我们通过调试网页知道,如下:(⭐如果无法调试网页,请看如何调试网页)
代码实现如下:
import urllib.request
from bs4 import BeautifulSoup
# 读取给定 url 的 html 代码
response = urllib.request.urlopen('https://www.hist.edu.cn/index/sy/kyyw.htm')
content = response.read().decode('utf-8')
# 转换读取到的 html 文档
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
# 获取转换后的 html 文档里属性 class=list-main-warp 的 div 标签的内容
divs = soup.find_all('div', {'class': "list-main-warp"})
# 从已获取的 div 标签的内容里获取 li 标签的内容
lis = divs[0].find_all('li')
# 遍历获取到的 lis 列表,并从中抓取链接和标题
for li in lis:
print(li.find_all('a')[0].get("href"))
print(li.find_all('a')[0].get("title"))
输出如下:
三、完整代码展示
import urllib.request
from bs4 import BeautifulSoup
# 读取给定 url 的 html 代码
response = urllib.request.urlopen('https://www.hist.edu.cn/index/sy/kyyw.htm')
content = response.read().decode('utf-8')
# 转换读取到的 html 文档
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
# 获取转换后的 html 文档里属性 class=list-main-warp 的 div 标签的内容
divs = soup.find_all('div', {'class': "list-main-warp"})
# 从已获取的 div 标签的内容里获取 li 标签的内容
lis = divs[0].find_all('li')
# 遍历获取到的 lis 列表,并从中抓取链接和标题
for li in lis:
print(li.find_all('a')[0].get("href"))
print(li.find_all('a')[0].get("title"))
四、总结
至此,我们已经使用了urllib库和BeautifulSoup库以及网页的基础知识来爬取学校官网的新闻标题和链接。如果你细心,你会发现我们目前只能获取一页的新闻标题和链接数据,并获取它们。的新闻链接仍然是相对路径。它不是可以立即使用的链接。它只能在转换后使用。然而,学校新闻不止一页。我们希望能够抓取所有页面的新闻标题和链接,而我们希望得到的新闻链接是绝对路径,能否存储抓取到的数据?如何实现这些功能?
点击查看Pola的Python资料采集-爬取学校官网新闻标题和链接(高级)继续学习!