溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python爬蟲技術(shù)入門實(shí)例代碼分析

發(fā)布時(shí)間:2023-04-04 11:35:43 來(lái)源:億速云 閱讀:112 作者:iii 欄目:開發(fā)技術(shù)

這篇“Python爬蟲技術(shù)入門實(shí)例代碼分析”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“Python爬蟲技術(shù)入門實(shí)例代碼分析”文章吧。

爬蟲技術(shù)基礎(chǔ)概念

  1. 爬蟲:自動(dòng)獲取網(wǎng)絡(luò)數(shù)據(jù)的程序。

  2. Web頁(yè)面結(jié)構(gòu):HTML、CSS、JavaScript等。

  3. HTTP請(qǐng)求:客戶端向服務(wù)器請(qǐng)求數(shù)據(jù)的方式。

  4. HTTP響應(yīng):服務(wù)器返回給客戶端的數(shù)據(jù)。

請(qǐng)求與響應(yīng)

使用Python的requests庫(kù)發(fā)送HTTP請(qǐng)求。

import requests
 
url = "https://www.example.com"
response = requests.get(url)

獲取響應(yīng)內(nèi)容

html_content = response.text

HTML解析與數(shù)據(jù)提取

使用BeautifulSoup庫(kù)解析HTML內(nèi)容。

from bs4 import BeautifulSoup
 
soup = BeautifulSoup(html_content, "html.parser")

使用CSS選擇器或其他方法提取數(shù)據(jù)。

title = soup.title.string

實(shí)戰(zhàn):爬取簡(jiǎn)書網(wǎng)站首頁(yè)文章信息

發(fā)送請(qǐng)求,獲取簡(jiǎn)書網(wǎng)站首頁(yè)HTML內(nèi)容。

import requests
from bs4 import BeautifulSoup
 
url = "https://www.jianshu.com"
response = requests.get(url)
html_content = response.text

存儲(chǔ)數(shù)據(jù)

將數(shù)據(jù)存儲(chǔ)為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)

測(cè)試與優(yōu)化

1.遇到反爬蟲策略時(shí),可以使用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()函數(shù)控制請(qǐng)求頻率。

import time
 
time.sleep(10)

3.錯(cuò)誤處理與異常捕獲。

try:
    response = requests.get(url, headers=headers, timeout=5)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")

網(wǎng)站爬蟲完整代碼:

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.")

補(bǔ)充

為了更好地理解這個(gè)實(shí)戰(zhàn)項(xiàng)目,我們需要了解一些基礎(chǔ)概念和原理,這將有助于掌握Python的網(wǎng)絡(luò)編程和爬蟲技術(shù)。以下是一些基本的網(wǎng)絡(luò)爬蟲概念:

  1. HTTP協(xié)議:超文本傳輸協(xié)議(HTTP)是一種用于傳輸超媒體文檔(如 HTML)的應(yīng)用層協(xié)議。HTTP協(xié)議被用于從Web服務(wù)器傳輸或發(fā)布到Web瀏覽器或其他客戶端的數(shù)據(jù)。

  2. HTML、CSS 和 JavaScript:HTML 是用來(lái)描述網(wǎng)頁(yè)的一種語(yǔ)言。CSS 是用來(lái)表現(xiàn) HTML 結(jié)構(gòu)的樣式。JavaScript 是網(wǎng)頁(yè)編程的一種腳本語(yǔ)言,主要用于實(shí)現(xiàn)網(wǎng)頁(yè)上的動(dòng)態(tài)效果和與用戶的交互。

  3. DOM:文檔對(duì)象模型(DOM)是一種跨平臺(tái)的編程接口,用于處理 HTML 和 XML 文檔。DOM將文檔視為樹形結(jié)構(gòu),其中每個(gè)節(jié)點(diǎn)代表一個(gè)部分(如元素、屬性或文本)。

  4. URL:統(tǒng)一資源定位符(URL)是用于指定互聯(lián)網(wǎng)資源位置的一種字符串。

  5. 請(qǐng)求頭(Request Headers):在HTTP請(qǐng)求中,請(qǐng)求頭包含了關(guān)于客戶端的環(huán)境、瀏覽器等信息。常見的請(qǐng)求頭字段有:User-Agent、Accept、Referer 等。

  6. 響應(yīng)頭(Response Headers):在HTTP響應(yīng)中,響應(yīng)頭包含了關(guān)于服務(wù)器的信息、響應(yīng)狀態(tài)碼等信息。常見的響應(yīng)頭字段有:Content-Type、Content-Length、Server 等。

  7. 網(wǎng)絡(luò)爬蟲策略:有些網(wǎng)站會(huì)采取一些策略來(lái)阻止爬蟲抓取數(shù)據(jù),如:封禁IP、限制訪問(wèn)速度、使用 JavaScript 動(dòng)態(tài)加載數(shù)據(jù)等。在實(shí)際應(yīng)用中,我們需要根據(jù)這些策略采取相應(yīng)的應(yīng)對(duì)措施,如:使用代理IP、限制爬蟲抓取速度、使用瀏覽器模擬庫(kù)(如 Selenium)等。

以上就是關(guān)于“Python爬蟲技術(shù)入門實(shí)例代碼分析”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI