- 每个节点都是一个网页
- 每条边都是一个超链接
- 网络爬虫就是从这样一个网络图中抓取感兴趣的内容
import requests# 导入网页请求库
from bs4 import BeautifulSoup# 导入网页解析库
import csv
from tqdm import tqdm
# 模拟浏览器访问
Headers = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400'
# 表头
csvHeaders = ['题号', '难度', '标题', '通过率', '通过数/总提交数']
# 题目数据
subjects = []
# 爬取题目
print('题目信息爬取中:\n')
for pages in tqdm(range(1, 11 + 1)):
# 传入URL
r = requests.get(f'http://www.51mxd.cn/problemset.php-page={pages}.htm', Headers)
r.raise_for_status()
r.encoding = 'utf-8'
# 解析URL
soup = BeautifulSoup(r.text, 'html5lib')
#查找爬取与td相关所有内容
td = soup.find_all('td')
subject = []
for t in td:
if t.string is not None:
subject.append(t.string)
if len(subject) == 5:
subjects.append(subject)
subject = []
# 存放题目
with open('NYOJ_Subjects.csv', 'w', newline='') as file:
fileWriter = csv.writer(file)
fileWriter.writerow(csvHeaders)
fileWriter.writerows(subjects)
print('\n题目信息爬取完成!!!')
点击运行后生成NYOJ_Subjects.csv文件,打开该文件
2.本次调用了 requests网页请求库和Beautiful Soup网页解析库
import requests# 导入网页请求库
from bs4 import BeautifulSoup# 导入网页解析库
3.定义访问浏览器所需的请求头和写入csv文件需要的表头以及存放题目数据的列表
# 模拟浏览器访问
# 模拟浏览器访问
Headers = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400'
# 表头
csvHeaders = ['题号', '难度', '标题', '通过率', '通过数/总提交数']#表头列表
# 题目数据
subjects = []#定义列表存放数据
4.根据表头csvHeaders中内容爬取信息,并在进度条中显示进度
# 爬取题目
print('题目信息爬取中:\n')
for pages in tqdm(range(1, 11 + 1)):#一页一页地爬取信息
# 传入URL
r = requests.get(f'http://www.51mxd.cn/problemset.php-page={pages}.htm', Headers)
r.raise_for_status()
r.encoding = 'utf-8'#输出文档为utf-8编码
# 解析URL
soup = BeautifulSoup(r.text, 'html5lib')
#查找爬取与csvHeaders表头中相关所有内容
td = soup.find_all('td')
subject = []#新定义一个subject用来存放当前页面爬取的满足特征的信息
for t in td:
if t.string is not None:
subject.append(t.string)
if len(subject) == 5:#通过长度判断subject内容是否爬取到上面5项
subjects.append(subject)#把subject存放进上面的subjects中
subject = []#subject置空
5.把爬取内容存放文件NYOJ_Subjects.csv中
# 存放题目
with open('NYOJ_Subjects.csv', 'w', newline='') as file:
fileWriter = csv.writer(file)
fileWriter.writerow(csvHeaders)
fileWriter.writerows(subjects)
print('\n题目信息爬取完成!!!')
1.进入网站http://news.cqjtu.edu.cn/xxtz.htm
2.鼠标空白处点击
后选择检查N
3.可以观察到需要爬取时间和标题所在位置
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 17 14:39:03 2021
@author: 86199
"""
import requests
from bs4 import BeautifulSoup
import csv
from tqdm import tqdm
import urllib.request, urllib.error # 制定URL 获取网页数据
# 所有新闻
subjects = []
# 模拟浏览器访问
Headers = { # 模拟浏览器头部信息
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.53"
}
# 表头
csvHeaders = ['时间', '标题']
print('信息爬取中:\n')
for pages in tqdm(range(1, 65 + 1)):
# 发出请求
request = urllib.request.Request(f'http://news.cqjtu.edu.cn/xxtz/{pages}.htm', headers=Headers)
html = ""
# 如果请求成功则获取网页内容
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
# 解析网页
soup = BeautifulSoup(html, 'html5lib')
# 存放一条新闻
subject = []
# 查找所有li标签
li = soup.find_all('li')
for l in li:
# 查找满足条件的div标签
if l.find_all('div',class_="time") is not None and l.find_all('div',class_="right-title") is not None:
# 时间
for time in l.find_all('div',class_="time"):
subject.append(time.string)
# 标题
for title in l.find_all('div',class_="right-title"):
for t in title.find_all('a',target="_blank"):
subject.append(t.string)
if subject:
print(subject)
subjects.append(subject)
subject = []
# 保存数据
with open('test.csv', 'w', newline='',encoding='utf-8') as file:
fileWriter = csv.writer(file)
fileWriter.writerow(csvHeaders)
fileWriter.writerows(subjects)
print('\n信息爬取完成!!!')
网络爬虫需要一定的Web基础,需要分析所要获取的内容信息的存放位置后设置条件进行爬虫。Python中通过调用库来进行爬虫获取信息比较简单方便。
基础篇-爬虫基本原理
爬虫-Python编程入门
基于python爬取重庆交通大学新闻网内容