python 爬虫基本使用——统计杭电oj题目正确率并排序
作者:颀周 时间:2021-11-25 17:16:35
python爬虫主要用两个库:Urllib和BeautifulSoup4。一个用来爬取网页,一个用来解析网页。
Urllib是Python内置的HTTP请求库,它包含四个模块:
1、request,最基本的 HTTP 请求模块,用来模拟发送请求,就像在浏览器里输入网址然后敲击回车一样,只需要给库方法传入 URL 与额外的参数,就可以模拟这个过程。
2、error ,异常处理模块,如果出现请求错误,我们可以捕获这些异常,然后进行重试或其他操作保证程序不会意外终止。
3、parse ,工具模块,提供了许多 URL 处理方法,比如拆分、解析、合并等。
4、robotparser,主要用于识别网站的 robots.txt 文件,判断网站是否可以爬取,用的较少。
这里只用到了最常用的request。
BeautifulSoup4从bs4包中导出,这里主要用的就是它的解析功能。
代码如下,注释写得很清楚了:
#杭电OJ题目AC率排序
import urllib.request as ur
from bs4 import BeautifulSoup
dic = {} #存:"题号:题名 AC 提交次数 正确率"
for t in range(1,59,1):#1~58页都爬一遍
print(t)
url = 'http://acm.hdu.edu.cn/listproblem.php?vol='+str(t) #存网址
bs = BeautifulSoup(ur.urlopen(url).read(),"html.parser")#获取网址的html并转换为可以python可以使用的结构
ql0 = str(bs.body.table.contents[11].td.table.contents[1])#网页的DOM解析后可以直接通过"."来寻找子元素,找到题目的列表元素后,将列表中所有题目转换成字符串。(可以输出看看)
ql = ql0[30:-10].split(";") #字符串中的题目以";"分隔,将它们分开,并存到列表中
for i in ql: #以下就是格式化处理每个题目,然后存到字典中
info1 = i.split(',"',1)
num = info1[0].split(',')[1]
info2 = info1[1].split('",',1)
name = info2[0]
right,submit = info2[1].split(',',1)
submit = submit[:-1]
dic[num] = [name,int(right),int(submit),int(right)/int(submit)]
dic = sorted(dic.items(),key = lambda x: x[1][3]) #每页题目都存入字典后,把字典中的题目通过正确率进行排序,传出列表
with open('Statistics.txt','w',encoding = 'utf-8') as f:#把统计排序好的题目保存到txt中
for i in dic:
f.write(str(i)+'\n')
print("Success!")
来源:https://www.cnblogs.com/qizhou/p/13030209.html
标签:python,爬虫,统计
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
YUI3设计中的激进和妥协
2010-01-17 09:59:00
Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)
2021-01-23 04:23:13
javascript二维数组转置实例
2023-08-25 07:11:14
ASP程序中输出Excel文件实例一则
2008-11-07 15:29:00
让你的空间支持域名绑定子目录的解决办法
2010-09-15 10:03:00
详解python变量与数据类型
2021-09-24 14:38:32
oracle下加密存储过程的方法
2009-02-28 10:50:00
python 名称空间与作用域详情
2021-06-10 23:12:38
![](https://img.aspxhome.com/file/2023/8/71548_0s.png)
使用Python画了一棵圣诞树的实例代码
2022-06-18 23:55:04
![](https://img.aspxhome.com/file/2023/2/66402_0s.png)
asp防止盗链HTTP_REFERER判断代码
2010-03-12 10:41:00
ASP编程入门进阶(十三):AdRotator & Content Rotator
2008-09-24 17:47:00
基于python实现垂直爬虫系统的方法详解
2023-11-17 13:33:38
python复制文件到指定目录的实例
2021-03-17 17:10:26
Pytest+request+Allure实现接口自动化框架
2023-08-12 17:29:33
![](https://img.aspxhome.com/file/2023/7/64297_0s.jpg)
详尽讲述用Python的Django框架测试驱动开发的教程
2023-04-21 18:28:19
![](https://img.aspxhome.com/file/2023/1/75921_0s.png)
python编写softmax函数、交叉熵函数实例
2023-11-24 07:08:11
![](https://img.aspxhome.com/file/2023/6/64606_0s.jpg)
[原创][分享]数字格式化转换
2011-07-04 12:20:15
jQuery 1.4 Released 新特性官方诠释
2010-04-01 12:23:00
![](https://img.aspxhome.com/file/UploadPic/20104/1/4271690739_f0bced3a78-60s.jpg)
使用python的turtle绘画滑稽脸实例
2022-04-18 02:24:49
![](https://img.aspxhome.com/file/2023/1/66301_0s.jpg)
详解Python中string模块除去Str还剩下什么
2021-08-25 12:48:19