爬蟲技術基礎概念
爬蟲:自動取得網路資料的程式。
Web頁面架構:HTML、CSS、JavaScript等。
HTTP請求:客戶端向伺服器請求資料的方式。
HTTP回應:伺服器傳回給客戶端的資料。
請求與回應
使用Python的requests函式庫發送HTTP請求。
import requests url = "https://www.example.com" response = requests.get(url)
取得回應內容
html_content = response.text
HTML解析與資料擷取
#使用BeautifulSoup函式庫解析HTML內容。
from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, "html.parser")
使用CSS選擇器或其他方法擷取資料。
title = soup.title.string
實戰:爬取簡書網站首頁文章資訊
發送請求,取得簡書網站首頁HTML內容。
import requests from bs4 import BeautifulSoup url = "https://www.jianshu.com" response = requests.get(url) html_content = response.text
儲存資料
將資料儲存為JSON格式。
import json with open("jianshu_articles.json", "w", encoding="utf-8") as f: json.dump(article_info_list, f, ensure_ascii=False, indent=4)
測試與最佳化
1.遇到反爬蟲策略時,可以使用User-Agent偽裝成瀏覽器。
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} response = requests.get(url, headers=headers)
2.使用time.sleep()函數控制請求頻率。
import time time.sleep(10)
3.錯誤處理與異常捕獲。
try: response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error: {e}")
網站爬蟲完整程式碼:
import requests from bs4 import BeautifulSoup import json import time def fetch_jianshu_articles(): url = "https://www.jianshu.com" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} try: response = requests.get(url, headers=headers, timeout=5) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"Error: {e}") return html_content = response.text soup = BeautifulSoup(html_content, "html.parser") articles = soup.find_all("div", class_="content") article_info_list = [] for article in articles: title = article.h3.text.strip() author = article.find("span", class_="name").text.strip() link = url + article.h3.a["href"] article_info = {"title": title, "author": author, "link": link} article_info_list.append(article_info) return article_info_list def save_to_json(article_info_list, filename): with open(filename, "w", encoding="utf-8") as f: json.dump(article_info_list, f, ensure_ascii=False, indent=4) if __name__ == "__main__": article_info_list = fetch_jianshu_articles() if article_info_list: save_to_json(article_info_list, "jianshu_articles.json") print("Jianshu articles saved to 'jianshu_articles.json'.") else: print("Failed to fetch Jianshu articles.")
補充
為了更好地理解這個實戰項目,我們需要了解一些基礎概念和原理,這將有助於掌握Python的網路程式設計和爬蟲技術。以下是一些基本的網路爬蟲概念:
HTTP協定:超文本傳輸協定(HTTP)是用於傳輸超媒體文件(如 HTML)的應用層協定。 HTTP協定被用於從Web伺服器傳輸或發佈到網頁瀏覽器或其他客戶端的資料。
HTML、CSS 和 JavaScript:HTML 是用來描述網頁的語言。 CSS 是用來表現 HTML 結構的樣式。 JavaScript 是網頁程式設計的一種腳本語言,主要用於實現網頁上的動態效果和與使用者的互動。
DOM:文件物件模型(DOM)是一種跨平台的程式設計接口,用於處理 HTML 和 XML 文件。 DOM將文件視為樹狀結構,其中每個節點代表一個部分(如元素、屬性或文字)。
URL:統一資源定位符(URL)是用來指定網路資源位置的一種字串。
請求頭(Request Headers):在HTTP請求中,請求頭包含了關於客戶端的環境、瀏覽器等資訊。常見的請求頭字段有:User-Agent、Accept、Referer 等。
回應頭(Response Headers):在HTTP回應中,回應頭包含了關於伺服器的資訊、回應狀態碼等資訊。常見的回應標頭欄位有:Content-Type、Content-Length、Server 等。
網路爬蟲策略:有些網站會採取一些策略來阻止爬蟲抓取數據,如:封鎖IP、限制存取速度、使用 JavaScript 動態載入資料等。在實際應用中,我們需要根據這些策略採取相應的應對措施,如:使用代理IP、限制爬蟲抓取速度、使用瀏覽器模擬庫(如 Selenium)等。
以上是Python爬蟲技術入門實例程式碼解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

ArraySareBetterForlement-WiseOperationsDuetofasterAccessCessCessCessCessCessCessCessAndOptimizedImplementations.1)ArrayshaveContiguucuulmemoryfordirectAccesscess.2)列出sareflexible butslible butslowerduetynemicizing.3)

在NumPy中进行整个数组的数学运算可以通过向量化操作高效实现。1)使用简单运算符如加法(arr 2)可对数组进行运算。2)NumPy使用C语言底层库,提升了运算速度。3)可以进行乘法、除法、指数等复杂运算。4)需注意广播操作,确保数组形状兼容。5)使用NumPy函数如np.sum()能显著提高性能。

在Python中,向列表插入元素有兩種主要方法:1)使用insert(index,value)方法,可以在指定索引處插入元素,但在大列表開頭插入效率低;2)使用append(value)方法,在列表末尾添加元素,效率高。對於大列表,建議使用append()或考慮使用deque或NumPy數組來優化性能。

tomakeapythonscriptexecutableonbothunixandwindows:1)addashebangline(#!/usr/usr/bin/envpython3)Andusechmod xtomakeitexecutableonix.2)onWindows,確保pytythonisinstalledandassionstalledandassociatedwith.pyfiles,oruseabatchfile(runun.batchfile(runitter)(rugitty.batt)

當遇到“commandnotfound”錯誤時,應檢查以下幾點:1.確認腳本存在且路徑正確;2.檢查文件權限,必要時使用chmod添加執行權限;3.確保腳本解釋器已安裝並在PATH中;4.驗證腳本開頭的shebang行是否正確。這樣做可以有效解決腳本運行問題,確保編碼過程順利進行。

ArraySareAryallyMoremory-Moremory-forigationDataDatueTotheIrfixed-SizenatureAntatureAntatureAndirectMemoryAccess.1)arraysStorelelementsInAcontiguxufulock,ReducingOveringOverheadHeadefromenterSormetormetAdata.2)列表,通常

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python列表可以存儲不同類型的數據。示例列表包含整數、字符串、浮點數、布爾值、嵌套列表和字典。列表的靈活性在數據處理和原型設計中很有價值,但需謹慎使用以確保代碼的可讀性和可維護性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能