Python实验项目9 :网络爬虫与自动化

实验 1:爬取网页中的数据。

要求:使用 urllib 库和 requests 库分别爬取 http://www.sohu.com 首页的前 360 个字节的数据。

python 复制代码
# 要求:使用 urllib 库和 requests 库分别爬取 http://www.sohu.com 首页的前 360 个字节的数据。
import urllib.request
import requests
# 使用 urllib 库爬取 http://www.sohu.com 首页的前 360 个字节的数据。
url = 'http://www.sohu.com'
req = urllib.request.Request(url)
res = urllib.request.urlopen(req)
data = res.read(360)
print(data)


# 使用 requests 库爬取 http://www.sohu.com 首页的前 360 个字节的数据。
#url = 'http://www.sohu.com'
#res = requests.get(url)
#data = res.content[:360]
#print(data)

实验 2 :测试 BeautifulSoup 对象的方法。

要求:

1)创建 BeautifulSoup 对象。
2)测试搜索文档树的 find_all()方法和 find()方法。
python 复制代码
# 实验 2:测试 BeautifulSoup 对象的方法。
# 要求:
# 1)创建 BeautifulSoup 对象。
# 2)测试搜索文档树的 find_all()方法和 find()方法。
from bs4 import BeautifulSoup
import requests
# 过http请求加载网页
response = requests.get("http://www.sohu.com")
# 创建BeautifulSoup对象
soup = BeautifulSoup(response.text, "html.parser")
# 搜索文档树的find_all()方法
print(soup.find_all("a"))
# 搜索文档树的find()方法
print(soup.find("a"))

实验 3:爬取并分析网页页面数据。

(1 )使用 requests 库爬取 https://www.hnnu.edu.cn/main.htm首页内容。
(2)编写程序获取 https://www.hnnu.edu.cn/119/list.htm****的通知公告的信息。
python 复制代码
# 实验 3:爬取并分析网页页面数据。
# (1)使用requests库爬取https://www.hnnu.edu.cn/main.htm首页内容。
# (2)编写程序获取https://www.hnnu.edu.cn/119/list.htm的通知公告的信息。
import requests
from bs4 import BeautifulSoup
url = 'https://www.hnnu.edu.cn/main.htm'
res = requests.get(url)
soup = BeautifulSoup(res.text,'html.parser')
print(soup.find_all('a'))
print(soup.find('a'))

for i in range(1,23,1):
    url = 'https://www.hnnu.edu.cn/119/list.htm{}.htm'.format(i)
    res = requests.get(url)
    soup = BeautifulSoup(res.text,'html.parser')
    print("-------------------------------------------------------")
    print(soup)
    #print(soup.find('a'))
相关推荐
学习是种信仰几秒前
复现conda环境及Python 项目路径(PYTHONPATH)问题——基于Ubuntu
python·ubuntu·conda
AI玫瑰助手3 分钟前
Python流程控制:if-else与if-elif-else嵌套使用
开发语言·python·信息可视化
无限进步_4 分钟前
【C++】深入底层:自己动手实现一个哈希表
开发语言·数据结构·c++·算法·链表·散列表·visual studio
贵州晓智信息科技8 分钟前
学词鸭 Typing 无痛背单词
人工智能·pytorch·python·深度学习
小杍随笔11 分钟前
【在 Rust + Tauri 2 应用中实现语言切换功能:完整技术指南】
开发语言·后端·rust
minji...15 分钟前
Linux 网络基础之UDP协议(四)传输层协议 UDP,再谈端口号,UDP 特点
linux·服务器·开发语言·网络·c++·tcp/ip·udp
逻辑驱动的ken15 分钟前
Java高频面试考点场景题27
java·开发语言·面试·职场和发展·求职招聘
清水白石00820 分钟前
从手写初始化到 pytest fixture:让 Python 测试既干净、可复用,又能驾驭异步并发
开发语言·python·pytest
不知名的老吴25 分钟前
关于C++中new的基本使用方法介绍
开发语言·c++