一文教你Python如何快速精準(zhǔn)抓取網(wǎng)頁(yè)數(shù)據(jù)
本文將使用requests和BeautifulSoup這兩個(gè)流行的庫(kù)來(lái)實(shí)現(xiàn)。
1. 準(zhǔn)備工作
首先安裝必要的庫(kù):
pip install requests beautifulsoup4
2. 基礎(chǔ)爬蟲實(shí)現(xiàn)
import requests from bs4 import BeautifulSoup import time import random def get_csdn_articles(keyword, pages=1): """ 抓取CSDN上指定關(guān)鍵詞的文章 :param keyword: 搜索關(guān)鍵詞 :param pages: 要抓取的頁(yè)數(shù) :return: 文章列表,包含標(biāo)題、鏈接、簡(jiǎn)介等信息 """ headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } base_url = "https://so.csdn.net/so/search" articles = [] for page in range(1, pages + 1): params = { 'q': keyword, 't': 'blog', 'p': page } try: response = requests.get(base_url, headers=headers, params=params) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') items = soup.find_all('div', class_='search-item') for item in items: title_tag = item.find('a', class_='title') if not title_tag: continue title = title_tag.get_text().strip() link = title_tag['href'] # 獲取簡(jiǎn)介 desc_tag = item.find('p', class_='content') description = desc_tag.get_text().strip() if desc_tag else '無(wú)簡(jiǎn)介' # 獲取閱讀數(shù)和發(fā)布時(shí)間 info_tags = item.find_all('span', class_='date') read_count = info_tags[0].get_text().strip() if len(info_tags) > 0 else '未知' publish_time = info_tags[1].get_text().strip() if len(info_tags) > 1 else '未知' articles.append({ 'title': title, 'link': link, 'description': description, 'read_count': read_count, 'publish_time': publish_time }) print(f"已抓取第 {page} 頁(yè),共 {len(items)} 篇文章") # 隨機(jī)延遲,避免被封 time.sleep(random.uniform(1, 3)) except Exception as e: print(f"抓取第 {page} 頁(yè)時(shí)出錯(cuò): {e}") continue return articles if __name__ == '__main__': # 示例:抓取關(guān)于"Python爬蟲"的前3頁(yè)文章 keyword = "
3. 高級(jí)功能擴(kuò)展
3.1 抓取文章詳情
def get_article_detail(url): """抓取文章詳情內(nèi)容""" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } try: response = requests.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # 獲取文章主體內(nèi)容 content = soup.find('article') if content: # 清理不必要的標(biāo)簽 for tag in content(['script', 'style', 'iframe', 'nav', 'footer']): tag.decompose() return content.get_text().strip() return "無(wú)法獲取文章內(nèi)容" except Exception as e: print(f"抓取文章詳情出錯(cuò): {e}") return None
3.2 保存數(shù)據(jù)到文件
import json import csv def save_to_json(data, filename): """保存數(shù)據(jù)到JSON文件""" with open(filename, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) def save_to_csv(data, filename): """保存數(shù)據(jù)到CSV文件""" if not data: return keys = data[0].keys() with open(filename, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=keys) writer.writeheader() writer.writerows(data)
4. 完整示例
if __name__ == '__main__': # 抓取文章列表 keyword = "Python爬蟲" articles = get_csdn_articles(keyword, pages=2) # 抓取前3篇文章的詳情 for article in articles[:3]: article['content'] = get_article_detail(article['link']) time.sleep(random.uniform(1, 2)) # 延遲 # 保存數(shù)據(jù) save_to_json(articles, 'csdn_articles.json') save_to_csv(articles, 'csdn_articles.csv') print("數(shù)據(jù)抓取完成并已保存!")
5. 反爬蟲策略應(yīng)對(duì)
1.設(shè)置請(qǐng)求頭:模擬瀏覽器訪問(wèn)
2.隨機(jī)延遲:避免請(qǐng)求過(guò)于頻繁
3.使用代理IP:防止IP被封
4.處理驗(yàn)證碼:可能需要人工干預(yù)
5.遵守robots.txt:尊重網(wǎng)站的爬蟲規(guī)則
到此這篇關(guān)于一文教你Python如何快速精準(zhǔn)抓取網(wǎng)頁(yè)數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Python抓取網(wǎng)頁(yè)數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 利用Python抓取網(wǎng)頁(yè)數(shù)據(jù)的多種方式與示例詳解
- Python使用BeautifulSoup和Scrapy抓取網(wǎng)頁(yè)數(shù)據(jù)的具體教程
- Python使用BeautifulSoup抓取和解析網(wǎng)頁(yè)數(shù)據(jù)的操作方法
- Python爬蟲之使用BeautifulSoup和Requests抓取網(wǎng)頁(yè)數(shù)據(jù)
- 淺談如何使用python抓取網(wǎng)頁(yè)中的動(dòng)態(tài)數(shù)據(jù)實(shí)現(xiàn)
- Python獲取網(wǎng)頁(yè)數(shù)據(jù)的五種方法
- Python實(shí)現(xiàn)快速抓取網(wǎng)頁(yè)數(shù)據(jù)的5種高效方法
相關(guān)文章
python中斷time.sleep一種更優(yōu)雅的方式:event.wait
這篇文章主要介紹了python中斷time.sleep一種更優(yōu)雅的方式:event.wait,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11python 讀取txt,json和hdf5文件的實(shí)例
今天小編就為大家分享一篇python 讀取txt,json和hdf5文件的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06Python爬蟲獲取JavaScript動(dòng)態(tài)渲染后的網(wǎng)頁(yè)內(nèi)容四種方法
在爬取動(dòng)態(tài)網(wǎng)頁(yè)數(shù)據(jù)時(shí)我們需要模擬客戶端瀏覽器環(huán)境,讓JavaScript能夠正常地執(zhí)行,并獲取渲染后的頁(yè)面數(shù)據(jù),這篇文章主要介紹了Python爬蟲獲取JavaScript動(dòng)態(tài)渲染后的網(wǎng)頁(yè)內(nèi)容四種方法,需要的朋友可以參考下2025-06-06python爬蟲 基于requests模塊發(fā)起ajax的get請(qǐng)求實(shí)現(xiàn)解析
這篇文章主要介紹了python爬蟲 基于requests模塊發(fā)起ajax的get請(qǐng)求實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08使用python將請(qǐng)求的requests headers參數(shù)格式化方法
今天小編就為大家分享一篇使用python將請(qǐng)求的requests headers參數(shù)格式化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01python開發(fā)之str.format()用法實(shí)例分析
這篇文章主要介紹了python開發(fā)之str.format()用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了str.format()函數(shù)的功能,使用方法與相關(guān)注意事項(xiàng),代碼包含詳盡的注釋說(shuō)明,需要的朋友可以參考下2016-02-02python類和函數(shù)中使用靜態(tài)變量的方法
這篇文章主要介紹了python類和函數(shù)中使用靜態(tài)變量的方法,實(shí)例分析了三種常用的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-05-05Python Socket編程實(shí)現(xiàn)猜數(shù)字游戲交互體驗(yàn)
當(dāng)利用Python的Socket編程創(chuàng)建一個(gè)猜數(shù)字游戲時(shí),需要分別實(shí)現(xiàn)服務(wù)器端和客戶端的邏輯,本文將詳細(xì)描述這兩個(gè)部分的功能和代碼片段2024-01-01python list元素為tuple時(shí)的排序方法
下面小編就為大家分享一篇python list元素為tuple時(shí)的排序方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04