网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。简单来说就是通过编写脚本模拟浏览器发起请求获取数据。爬虫从初始网页的URL开始, 获取初始网页上的URL,在抓取网页的过程中,不断从当前页面抽取新的url放入队列。直到满足系统给定的停止条件才停止。
我使用的IDE是pycharm,pycharm的导入库十分方便,可以在报错的库名处右键下载库
也可以点击file-setting-project里点击+号搜索需要的库
进入待爬取页面网站 http://www.51mxd.cn/problemset.php-page=1.htm
点击鼠标右键,查看源码
网址链接中.htm前数字与有关,所以可以可以通过一个循环爬取多页代码
for pages in tqdm(range(1, 11 + 1)):
r = requests.get(
f'http://www.51mxd.cn/problemset.php-page={pages}.htm', Headers)
找到爬取数据位置后,写代码
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)):
r = requests.get(
f'http://www.51mxd.cn/problemset.php-page={pages}.htm', Headers)
r.raise_for_status()
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'lxml')
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题目信息爬取完成!!!')
网站链接http://news.cqjtu.edu.cn/xxtz.htm
第二页网站http://news.cqjtu.edu.cn/xxtz.65htm
第三页网站http://news.cqjtu.edu.cn/xxtz.66htm
所以除了第一页,其他网站为http://news.cqjtu.edu.cn/xxtz.(67-n)htm
import requests
from bs4 import BeautifulSoup
import csv
def get_one_page(url):
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'
}
try:
info_list_page = []
resp = requests.get(url, headers=headers)
resp.encoding = resp.status_code
page_text = resp.text
soup = BeautifulSoup(page_text, 'lxml')
li_list = soup.select('.left-list > ul > li')
for li in li_list:
divs = li.select('div')
date = divs[0].string.strip()
title = divs[1].a.string
info = [date, title]
info_list_page.append(info)
except Exception as e:
print('爬取' + url + '错误')
print(e)
return None
else:
resp.close()
print('爬取' + url + '成功')
return info_list_page
def main():
info_list_all = []
base_url = 'http://news.cqjtu.edu.cn/xxtz/'
for i in range(1, 67):
if i == 1:
url = 'http://news.cqjtu.edu.cn/xxtz.htm'
else:
url = base_url + str(67 - i) + '.htm'
info_list_page = get_one_page(url)
info_list_all += info_list_page
with open('教务新闻.csv', 'w', newline='', encoding='utf-8') as file:
fileWriter = csv.writer(file)
fileWriter.writerow(['日期', '标题'])
fileWriter.writerows(info_list_all)
if __name__ == '__main__':
main()
https://blog.csdn.net/YangMax1/article/details/121305857?spm=1001.2014.3001.5501