学期:2021-2022学年第一学期
学 院 | 大数据与智能工程学院 | 年 级、 专 业、 班 | 18级数据科学与大数据技术(专升本)一班 | 姓 名 | 学号 | ||
---|---|---|---|---|---|---|---|
实验项目 名称 | 抓取学院网站的新闻内容的标题,发布时间 |
实验学时: 3h 同组学生姓名: 王美琴、尤博欣、周青青、李昕辰 实验地点: 9317
实验日期: 实验成绩: 批改教师: 批改时间:
指导教师评阅:
- 实验目的:抓取学院网站的新闻内容的标题,发布时间
- 实验原理:requests请求、bs4网页解析
- 实验环境 :win11、python3.9、vscode、edge
- 实验步骤:
- Requests网页请求,获取网页源代码
- 使用bs4语法解析网页数据
- 返回学院网站的新闻内容的标题,发布时间等数据保存为txt文件
核心代码:
#http://www.tipdm.com/gsxw/index.jhtml
import urllib.request
from bs4 import BeautifulSoup
dress = 'http://www.tipdm.com/gsxw/index.jhtml'
contents = [["标题","时间","浏览量"]]
for i in range(1,54):
if i == 1 :
str_dress = dress
else:
str_dress = dress[0:-6]+'_'+str(i)+dress[-6::]
print(str_dress)
response = urllib.request.urlopen(str_dress)
data = response.read()
soup = BeautifulSoup(data, "lxml")
tags = soup.find_all("div", attrs={"class": "con"})
for tag in tags:
tag_a = tag.find("a")
print(tag_a)
d = tag_a["href"]
response = urllib.request.urlopen(d)
data = response.read()
soup = BeautifulSoup(data, "lxml")
content = []
try:
content.append(soup.find("h1").text.strip())
except AttributeError:
content.append("标题缺失!!!")
try:
content.append(soup.find("span", attrs={"class": "date"}).text.strip())
except AttributeError:
content.append("时间缺失!!!")
try:
content.append(soup.find("span", attrs={"class": "view"}).text.strip())
except AttributeError:
content.append("浏览量缺失!!!")
contents.append(content)
fo = open("A.txt","w")
for content in contents:
for i in content:
fo.write(i+" ")
fo.write("\r")
fo.close()
- 实验结果及分析:
通过requests库,并添加网页请求头,使用代理IP,请求网页url,得到网页数据源代码,并通过BeautifulSoup库使用bs4语法,进行数据整理提取,最后存入txt文件。
- 实验总结:
在进行网页爬取时,网站会存在一些反爬机制,如:是否添加请求头、IP访问是否超出网站限制等,在进行网站爬取时,需要注意网站的反爬机制,并使用相对应的反反爬,最终得到数据。