用Python爬取考研调剂信息

  1. 未加请求头时,会返回404,故添加header。
  2. 分析网页http://muchong.com/f-430-1为第一页,http://muchong.com/f-430-2为第二页
  3. 使用utf-8对网页内容解码时,会出现乱码。查看网页源代码, charset="gbk" ,故改为gbk编码。
  4. 通过查看元素得到标题,时间的标签和class。
  5. 写入markdown文件,方便打开查看。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import requests
from bs4 import BeautifulSoup

baseUrl = 'http://muchong.com/f-430-%d'
keywords = ["计算机", "软件工程"]


def getWebPageMessage(url, f):
url = url
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
req = requests.get(url, headers=header)
bsObj = BeautifulSoup(req.content.decode('gbk', 'ignore'), "html.parser")
forumList = bsObj.findAll("tr", {"class": "forum_list"})
for item in forumList:
title = item.find("a", {"class": "a_subject"}).get_text()
for keyword in keywords:
if title.find(keyword) is not -1:
date = item.findAll("cite")[1].get_text()
url = "http://muchong.com" + item.find("a", {"class": "a_subject"})['href']
f.write("|" + title + "|" + url + "|" + date + "|\n")


def main():
f = open('调剂信息.md', 'w')
f.write("| 标题 | 链接 | 日期 |\n")
f.write("| ---- | ---- | ---- |\n")
page = 1 # 初始页码
for i in range(3):
getWebPageMessage(baseUrl % page, f)
page = page + 1
f.close()


if __name__ == '__main__':
main()

结果展示:

打开markdown文件后,结果如下:

标题 链接 日期
东北石油大学软件工程专业接收校内外调剂考生。 http://muchong.com/t-14087831-1 2020-02-24 14:35:59
广西师范大学计算机与信息工程学院 陈明教授课题组招收计算机与自动化方向调剂生3名 http://muchong.com/t-14091609-1 2020-02-24 14:35:01
【学硕】福建农林大学计算机科学与技术专业杨长才课题组招收调剂生4名 http://muchong.com/t-14091329-1 2020-02-24 14:34:21
题目:计算机好的安全、数学、计算机等相关专业工科男(学硕)调剂信息 http://muchong.com/t-14091711-1 2020-02-24 14:33:37
接受计算机相关专业调剂! http://muchong.com/t-12213688-1 2020-02-24 13:50:25
2020接受考研调剂,计算机 http://muchong.com/t-14085143-1 2020-02-24 13:39:40
济南大学智能计算与科学计算课题组拟接收计算机专业 (学术型) 硕士生调剂-预宣传 http://muchong.com/t-14077175-1 2020-02-24 13:35:59