Python爬蟲入門教程——爬取自己的部落格園部落格
網際網路時代裡,網路爬蟲是一種高效地資訊採集利器,可以快速準確地獲取網上的各種資料資源。本文使用Python庫requests、Beautiful Soup爬取CSDN部落格的相關資訊,利用txt檔案轉存。
基礎知識:
網路爬蟲是一種高效地資訊採集利器,利用它可以快速、準確地採集網際網路上的各種資料資源,幾乎已經成為大資料時代IT從業者的必修課。簡單點說,網路爬蟲就是獲取網頁並提取和儲存資訊的自動化過程,分為下列三個步驟:獲取網頁、提取資訊、儲存資料。
1.獲取網頁
使用requests傳送GET請求獲取網頁的原始碼。以獲取百度為例:
import requests response = requests.get('https://www.baidu.com') print(response.text)
2.提取資訊
Beautiful Soup是Python的一個HTML或XML解析庫,速度快,容錯能力強,可以方便、高效地從網頁中提取資料。基本用法:
from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'lxml') print(soup.prettify()) print(soup.title.string)
Beautiful Soup方法選擇器:
find_all()查詢符合條件的所有元素,返回所有匹配元素組成的列表。API如下:
find_all(name,attrs,recursive,text,**kwargs)
find()返回第一個匹配的元素。舉個栗子:
from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'lxml') print(soup.find('div', attrs={'class': 'article-list'}))
3.儲存資料
使用Txt文件儲存,相容性好。
使用with as語法。在with控制塊結束的時候,檔案自動關閉。舉個栗子:
with open(file_name, 'a') as file_object: file_object.write("I love programming.\n") file_object.write("I love playing basketball.\n")
分析頁面:
要爬取的頁面是部落格園“我的部落格”: ofollow,noindex">https://www.cnblogs.com/sgh1023/ 。
使用Chrome的開發者工具(快捷鍵F12),看到這個頁面的博文列表是一個id為mainContent的div。
在class為postTitle的div裡面可以找到連結和標題。
編寫程式碼:
獲取網頁使用requests ,提取資訊使用Beautiful Soup,儲存使用txt就可以了。
# coding: utf-8 import re import requests from bs4 import BeautifulSoup def get_blog_info(): headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Ubuntu Chromium/44.0.2403.89 ' 'Chrome/44.0.2403.89 ' 'Safari/537.36'} html = get_page(blog_url) soup = BeautifulSoup(html, 'lxml') article_list = soup.find('div', attrs={'id': 'mainContent'}) article_item = article_list.find_all('div', attrs={'class': 'postTitle'}) for ai in article_item: title = ai.a.text link = ai.a['href'] print(title) print(link) write_to_file(title+'\t') write_to_file(link+'\n') def get_page(url): try: headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.36 (KHTML, like Gecko) ' 'Ubuntu Chromium/44.0.2403.89 ' 'Chrome/44.0.2403.89 ' 'Safari/537.36'} response = requests.get(blog_url, headers=headers, timeout=10) return response.text except: return "" def write_to_file(content): with open('article.txt', 'a', encoding='utf-8') as f: f.write(content) if __name__ == '__main__': blog_url = "https://www.cnblogs.com/sgh1023/" get_blog_info()
爬取結果: