爬虫入门练习
目錄
- 網絡爬蟲
- 一、爬取[南陽理工OJ題目](http://www.51mxd.cn/problemset.php-page=1.htm)
- python代碼
- 結果
- 二、爬取[重交新聞](http://news.cqjtu.edu.cn/xxtz.htm)
- python代碼
- 結果
- 小結
網絡爬蟲
簡介
網絡爬蟲英文名叫Web Crawler戒WebSpider。是一種自動瀏覽網頁并采集所需要信息癿程序。
通過編寫腳本模擬瀏覽器發起請求獲取數據。爬蟲從初始網頁的URL開始, 獲取初始網頁上的URL,在抓取網頁的過程中,不斷從當前頁面抽取新的url放入隊列。直到滿足系統給定的停止條件才停止。
一、爬取南陽理工OJ題目
爬取每道題的題號,難度,標題,通過率,通過數/總提交數
python代碼
安裝第三方包requests,BeautifulSoup4
pip install requests pip install BeautifulSoup4 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') # tqdm作業:以進度條方式顯示爬取進度 # 爬取11頁所有題目信息 for pages in tqdm(range(1, 11 + 1)):# get請求第pages頁r = requests.get(f'http://www.51mxd.cn/problemset.php-page={pages}.htm', Headers)# 判斷異常r.raise_for_status()# 設置編碼r.encoding = 'utf-8'# 創建BeautifulSoup對象,用于解析該html頁面數據soup = BeautifulSoup(r.text, 'lxml')# 獲取所有td標簽td = soup.find_all('td')# 存放某一個題目的所有信息subject = []# 遍歷所有tdfor t in td:if t.string is not None:subject.append(t.string) # 獲取td中的字符串if len(subject) == 5: # 每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題目信息爬取完成!!!')結果
二、爬取重交新聞
爬取新聞的發布日期 和 標題
python代碼
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_codepage_text = resp.textsoup = BeautifulSoup(page_text, 'lxml')li_list = soup.select('.left-list > ul > li') # 找到所有li標簽for li in li_list:divs = li.select('div')date = divs[0].string.strip()title = divs[1].a.stringinfo = [date, title]info_list_page.append(info)except Exception as e:print('爬取' + url + '錯誤')print(e)return Noneelse:resp.close()print('爬取' + url + '成功')return info_list_page# main 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()結果
小結
分析所要獲取的內容信息的存放位置后設置條件進行網絡爬蟲。
鏈接
網絡爬蟲入門
總結
- 上一篇: C# 巧用anchor和dock设计复杂
- 下一篇: 获得数据库中表字段的名字.txt