爬取研招网,考研动态!一手情报,你考研过了吗?
爬取目标:
爬取研招网-考研动态所有的文章的的的的的
- 正文
- 标题
- 日期
- 来源
PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取
郑重声明:本项目及所有相关文章,仅用于经验技术交流,禁止将相关技术应用到不正当途径,因为滥用技术产生的风险与本人无关。
我是分割线....
1、导包
import csv import time import requests from bs4 import BeautifulSoup 1234
2、先获取所有文章链接
- 既然我们要爬取所有的文章,那就要先把所有文章的链接爬下来吧,然后再依次请求解析.
- 这里爬取链接用的是xpath,毕竟bs4的强项还是在处理文本上,下面获取具体内容全部用的bs4
- 这里就是为了获取 尾部url 即tail_url, 后面会用到,我们把所有的tail_url 放入到一个列表,后面会用到 (tail_url 是个人定义的一个变量,不是什么内置的东西…)
# 获取所有子路由,并保存到一个列表中 # 并未使用bs4解析器 Url_page_num = 0 tail_urls = [] for i in range(1, page_num): url = "https://yz.chsi.com.cn/kyzx/kydt/?start={}".format(Url_page_num) res=requests.get(url).text dom=etree.HTML(res) for list_num in range(1,51): tail_urls.append(dom.xpath('/html/body/div[1]/div[2]/div[3]/div[1]/ul/li[{}]/a/@href'.format(list_num))[0]) time.sleep(1) Url_page_num += 50 print(tail_urls) 123456789101112131415
2.1对一个文章使用bs4解析
先试试爬一个文章,后面直接for循环就行.
# 使用 bs4 对HTML解析 head_url = 'https://yz.chsi.com.cn' total_url = head_url + tail_urls[0] res=requests.get(total_url) soup = BeautifulSoup(res.content, 'lxml') # 获取正文 art_content = soup.find(class_="content-l detail").get_text() # 获取文章的标题、日期、来源 art_head = soup.find(class_="title-box").get_text().split("\n") art_title, art_date, art_source = art_head[1], art_head[2].split("日")[0] + "日", art_head[3].strip() art_title, art_date, art_source 12345678910111213
2.2 一个文章的结果:
似乎看起来很不错~~下面我们只需要添加for循环,然后写入csv就可以了. : )
3 、爬取所有
head_url = 'https://yz.chsi.com.cn' one_Page_result = [] for tail_url in tail_urls: # 拼接好了url,就请求,然后对网页解析 total_url = head_url + tail_url res=requests.get(total_url) soup = BeautifulSoup(res.content, 'lxml') # 获取文章的标题、日期、来源 art_head = soup.find(class_="title-box").get_text().split("\n") art_title, art_date, art_source = art_head[1], art_head[2].split("日")[0] + "日", art_head[3].strip() # 获取正文 art_content = soup.find(class_="content-l detail").get_text() one_Page_result.append(art_title) one_Page_result.append(art_date) one_Page_result.append(art_source) one_Page_result.append(art_content) with open("art_All.csv", "a+") as f: writer = csv.writer(f, dialect="excel") # 基于文件对象构建 csv写入对象 csv_write = csv.writer(f) csv_data = one_Page_result # 存入 csv_write.writerow(csv_data) f.close() print(art_title, art_date+"写入成功", "标记:"+tail_url) 123456789101112131415161718192021222324252627
爬取结果:
最后(爬虫)声明:
我贼怂, 如果本篇文章涉及了某平台的利益,请联系我,立马删除
本篇仅供参考学习,如若用于商业用途,后果自负.