首頁  >  文章  >  後端開發  >  Python爬蟲技術入門實例程式碼解析

Python爬蟲技術入門實例程式碼解析

王林
王林轉載
2023-04-22 13:04:071178瀏覽

爬蟲技術基礎概念

  1. 爬蟲:自動取得網路資料的程式。

  2. Web頁面架構:HTML、CSS、JavaScript等。

  3. HTTP請求:客戶端向伺服器請求資料的方式。

  4. 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的網路程式設計和爬蟲技術。以下是一些基本的網路爬蟲概念:

  1. HTTP協定:超文本傳輸協定(HTTP)是用於傳輸超媒體文件(如 HTML)的應用層協定。 HTTP協定被用於從Web伺服器傳輸或發佈到網頁瀏覽器或其他客戶端的資料。

  2. HTML、CSS 和 JavaScript:HTML 是用來描述網頁的語言。 CSS 是用來表現 HTML 結構的樣式。 JavaScript 是網頁程式設計的一種腳本語言,主要用於實現網頁上的動態效果和與使用者的互動。

  3. DOM:文件物件模型(DOM)是一種跨平台的程式設計接口,用於處理 HTML 和 XML 文件。 DOM將文件視為樹狀結構,其中每個節點代表一個部分(如元素、屬性或文字)。

  4. URL:統一資源定位符(URL)是用來指定網路資源位置的一種字串。

  5. 請求頭(Request Headers):在HTTP請求中,請求頭包含了關於客戶端的環境、瀏覽器等資訊。常見的請求頭字段有:User-Agent、Accept、Referer 等。

  6. 回應頭(Response Headers):在HTTP回應中,回應頭包含了關於伺服器的資訊、回應狀態碼等資訊。常見的回​​應標頭欄位有:Content-Type、Content-Length、Server 等。

  7. 網路爬蟲策略:有些網站會採取一些策略來阻止爬蟲抓取數據,如:封鎖IP、限制存取速度、使用 JavaScript 動態載入資料等。在實際應用中,我們需要根據這些策略採取相應的應對措施,如:使用代理IP、限制爬蟲抓取速度、使用瀏覽器模擬庫(如 Selenium)等。

#

以上是Python爬蟲技術入門實例程式碼解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除