Python 爬蟲實戰(zhàn)(一):使用 requests 和 BeautifulSoup

Python 基礎(chǔ)

我之前寫的《Python 3 極簡教程.pdf》幅恋,適合有點編程基礎(chǔ)的快速入門捆交,通過該系列文章學(xué)習(xí)品追,能夠獨立完成接口的編寫诵盼,寫寫小東西沒問題风宁。

requests

requests戒财,Python HTTP 請求庫捺弦,相當(dāng)于 Android 的 Retrofit幽崩,它的功能包括 Keep-Alive 和連接池慌申、Cookie 持久化蹄溉、內(nèi)容自動解壓柒爵、HTTP 代理棉胀、SSL 認(rèn)證膏蚓、連接超時驮瞧、Session 等很多特性论笔,同時兼容 Python2 和 Python3狂魔,GitHub:https://github.com/requests/requests

安裝

Mac:

pip3 install requests

Windows:

pip install requests

發(fā)送請求

HTTP 請求方法有 get、post烈评、put讲冠、delete。

import requests

# get 請求
response = requests.get('http://127.0.0.1:1024/developer/api/v1.0/all')

# post 請求
response = requests.post('http://127.0.0.1:1024/developer/api/v1.0/insert')

# put 請求
response = requests.put('http://127.0.0.1:1024/developer/api/v1.0/update')

# delete 請求
response = requests.delete('http://127.0.0.1:1024/developer/api/v1.0/delete')

請求返回 Response 對象否彩,Response 對象是對 HTTP 協(xié)議中服務(wù)端返回給瀏覽器的響應(yīng)數(shù)據(jù)的封裝肌毅,響應(yīng)的中的主要元素包括:狀態(tài)碼悬而、原因短語笨奠、響應(yīng)首部般婆、響應(yīng) URL蔚袍、響應(yīng) encoding啤咽、響應(yīng)體等等。

# 狀態(tài)碼
print(response.status_code)

# 響應(yīng) URL
print(response.url)

# 響應(yīng)短語
print(response.reason)

# 響應(yīng)內(nèi)容
print(response.json())

定制請求頭

請求添加 HTTP 頭部 Headers芋膘,只要傳遞一個 dict 給 headers 關(guān)鍵字參數(shù)就可以了臂拓。

header = {'Application-Id': '19869a66c6',
          'Content-Type': 'application/json'
          }
response = requests.get('http://127.0.0.1:1024/developer/api/v1.0/all/', headers=header)

構(gòu)建查詢參數(shù)

想為 URL 的查詢字符串(query string)傳遞某種數(shù)據(jù)埃儿,比如:http://127.0.0.1:1024/developer/api/v1.0/all?key1=value1&key2=value2 童番,Requests 允許你使用 params 關(guān)鍵字參數(shù),以一個字符串字典來提供這些參數(shù)忽你。

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get("http://127.0.0.1:1024/developer/api/v1.0/all", params=payload)

還可以將 list 作為值傳入:

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
response = requests.get("http://127.0.0.1:1024/developer/api/v1.0/all", params=payload)

# 響應(yīng) URL
print(response.url)# 打痈贰:http://127.0.0.1:1024/developer/api/v1.0/all?key1=value1&key2=value2&key2=value3

post 請求數(shù)據(jù)

如果服務(wù)器要求發(fā)送的數(shù)據(jù)是表單數(shù)據(jù),則可以指定關(guān)鍵字參數(shù) data散庶。

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post("http://127.0.0.1:1024/developer/api/v1.0/insert", data=payload)

如果要求傳遞 json 格式字符串參數(shù)悲龟,則可以使用 json 關(guān)鍵字參數(shù)须教,參數(shù)的值都可以字典的形式傳過去。

obj = {
    "article_title": "小公務(wù)員之死2"
}
# response = requests.post('http://127.0.0.1:1024/developer/api/v1.0/insert', json=obj)

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

Requests 會自動解碼來自服務(wù)器的內(nèi)容秒旋。大多數(shù) unicode 字符集都能被無縫地解碼约计。請求發(fā)出后煤蚌,Requests 會基于 HTTP 頭部對響應(yīng)的編碼作出有根據(jù)的推測尉桩。

# 響應(yīng)內(nèi)容
# 返回是 是 str 類型內(nèi)容
# print(response.text())
# 返回是 JSON 響應(yīng)內(nèi)容
print(response.json())
# 返回是二進制響應(yīng)內(nèi)容
# print(response.content())
# 原始響應(yīng)內(nèi)容蜘犁,初始請求中設(shè)置了 stream=True
# response = requests.get('http://127.0.0.1:1024/developer/api/v1.0/all', stream=True)
# print(response.raw())

超時

如果沒有顯式指定了 timeout 值奏窑,requests 是不會自動進行超時處理的埃唯。如果遇到服務(wù)器沒有響應(yīng)的情況時墨叛,整個應(yīng)用程序一直處于阻塞狀態(tài)而沒法處理其他請求。

response = requests.get('http://127.0.0.1:1024/developer/api/v1.0/all', timeout=5)  # 單位秒數(shù)

代理設(shè)置

如果頻繁訪問一個網(wǎng)站模蜡,很容易被服務(wù)器屏蔽掉漠趁,requests 完美支持代理。

# 代理
proxies = {
    'http': 'http://127.0.0.1:1024',
    'https': 'http://127.0.0.1:4000',
}
response = requests.get('http://127.0.0.1:1024/developer/api/v1.0/all', proxies=proxies)

BeautifulSoup

BeautifulSoup忍疾,Python Html 解析庫闯传,相當(dāng)于 Java 的 jsoup。

安裝

BeautifulSoup 3 目前已經(jīng)停止開發(fā)膝昆,直接使用BeautifulSoup 4丸边。

Mac:

pip3 install beautifulsoup4

Windows:

pip install beautifulsoup4

安裝解析器

我用的是 html5lib,純 Python 實現(xiàn)的妹窖。

Mac:

pip3 install html5lib

Windows:

pip install html5lib

簡單使用

BeautifulSoup 將復(fù)雜 HTML 文檔轉(zhuǎn)換成一個復(fù)雜的樹形結(jié)構(gòu),每個節(jié)點都是 Python 對象。

解析

from bs4 import BeautifulSoup

def get_html_data():
    html_doc = """
    <html>
    <head>
    <title>WuXiaolong</title>
    </head>
    <body>
    <p>分享 Android 技術(shù)堂竟,也關(guān)注 Python 等熱門技術(shù)。</p>
    <p>寫博客的初衷:總結(jié)經(jīng)驗,記錄自己的成長铆农。</p>
    <p>你必須足夠的努力郊霎,才能看起來毫不費力购对!專注!精致镣衡!
    </p>
    <p class="Blog"><a s blog</a></p>
    <p class="WeChat"><a >公眾號:吳小龍同學(xué)</a> </p>
    <p class="GitHub"><a  class="sister" id="link3">GitHub</a></p>
    </body>
    </html>   
    """
    soup = BeautifulSoup(html_doc, "html5lib")

tag

tag = soup.head
print(tag)  # <head><title>WuXiaolong</title></head>
print(tag.name)  # head
print(tag.title)  # <title>WuXiaolong</title>
print(soup.p)  # <p>分享 Android 技術(shù)曾雕,也關(guān)注 Python 等熱門技術(shù)幅虑。</p>
print(soup.a['href'])  # 輸出 a 標(biāo)簽的 href 屬性:http://wuxiaolong.me/

注意:tag 如果多個匹配,返回第一個,比如這里的 p 標(biāo)簽筋搏。

查找

print(soup.find('p'))  # <p>分享 Android 技術(shù),也關(guān)注 Python 等熱門技術(shù)茶鹃。</p>

find 默認(rèn)也是返回第一個匹配的標(biāo)簽迄埃,沒找到匹配的節(jié)點則返回 None叠赦。如果我想指定查找鳞仙,比如這里的公眾號蚂蕴,可以指定標(biāo)簽的如 class 屬性值:

# 因為 class 是 Python 關(guān)鍵字鸟整,所以這里指定為 class_伴栓。
print(soup.find('p', class_="WeChat"))
# <p class="WeChat"><a >公眾號</a> </p>

查找所有的 P 標(biāo)簽:

for p in soup.find_all('p'):
    print(p.string) 

實戰(zhàn)

前段時間除师,有用戶反饋痕貌,我的個人 APP 掛了涯肩,雖然這個 APP 我已經(jīng)不再維護花履,但是我也得起碼保證它能正常運行芽世。大部分人都知道這個 APP 數(shù)據(jù)是爬來的(詳見:《手把手教你做個人app》),數(shù)據(jù)爬來的好處之一就是不用自己管數(shù)據(jù)诡壁,弊端是別人網(wǎng)站掛了或網(wǎng)站的 HTML 節(jié)點變了济瓢,我這邊就解析不到,就沒數(shù)據(jù)妹卿。這次用戶反饋旺矾,我在想要不要把他們網(wǎng)站數(shù)據(jù)直接爬蟲了,正好自學(xué) Python夺克,練練手箕宙,嗯說干就干,本來是想著先用 Python 爬蟲铺纽,MySQL 插入本地數(shù)據(jù)庫柬帕,然后 Flask 自己寫接口,用 Android 的 Retrofit 調(diào)狡门,再用 bmob sdk 插入 bmob……哎陷寝,費勁,感覺行不通其馏,后來我得知 bmob 提供了 RESTful凤跑,解決大問題,我可以直接 Python 爬蟲插入就好了叛复,這里我演示的是插入本地數(shù)據(jù)庫仔引,如果用 bmob,是調(diào) bmob 提供的 RESTful 插數(shù)據(jù)致扯。

網(wǎng)站選定

我選的演示網(wǎng)站:https://meiriyiwen.com/random 肤寝,大家可以發(fā)現(xiàn),每次請求的文章都不一樣抖僵,正好利用這點,我只要定時去請求缘揪,解析自己需要的數(shù)據(jù)耍群,插入數(shù)據(jù)庫就 OK 了。

創(chuàng)建數(shù)據(jù)庫

我直接用 NaviCat Premium 創(chuàng)建的找筝,當(dāng)然也可以用命令行蹈垢。
[圖片上傳失敗...(image-50eadd-1512955991188)]

創(chuàng)建表

創(chuàng)建表 article,用的 pymysql袖裕,表需要 id曹抬,article_title,article_author急鳄,article_content 字段谤民,代碼如下堰酿,只需要調(diào)一次就好了。

import pymysql


def create_table():
    # 建立連接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         db='python3learn')
    # 創(chuàng)建名為 article 數(shù)據(jù)庫語句
    sql = '''create table if not exists article (
    id int NOT NULL AUTO_INCREMENT, 
    article_title text,
    article_author text,
    article_content text,
    PRIMARY KEY (`id`)
    )'''
    # 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
    cursor = db.cursor()
    try:
        # 執(zhí)行 sql 語句
        cursor.execute(sql)
        # 提交事務(wù)
        db.commit()
        print('create table success')
    except BaseException as e:  # 如果發(fā)生錯誤則回滾
        db.rollback()
        print(e)

    finally:
        # 關(guān)閉游標(biāo)連接
        cursor.close()
        # 關(guān)閉數(shù)據(jù)庫連接
        db.close()


if __name__ == '__main__':
    create_table()

解析網(wǎng)站

首先需要 requests 請求網(wǎng)站张足,然后 BeautifulSoup 解析自己需要的節(jié)點触创。

import requests
from bs4 import BeautifulSoup


def get_html_data():
    # get 請求
    response = requests.get('https://meiriyiwen.com/random')

    soup = BeautifulSoup(response.content, "html5lib")
    article = soup.find("div", id='article_show')
    article_title = article.h1.string
    print('article_title=%s' % article_title)
    article_author = article.find('p', class_="article_author").string
    print('article_author=%s' % article.find('p', class_="article_author").string)
    article_contents = article.find('div', class_="article_text").find_all('p')
    article_content = ''
    for content in article_contents:
        article_content = article_content + str(content)
        print('article_content=%s' % article_content)

插入數(shù)據(jù)庫

這里做了一個篩選,默認(rèn)這個網(wǎng)站的文章標(biāo)題是唯一的为牍,插入數(shù)據(jù)時哼绑,如果有了同樣的標(biāo)題就不插入。

import pymysql


def insert_table(article_title, article_author, article_content):
    # 建立連接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         db='python3learn',
                         charset="utf8")
    # 插入數(shù)據(jù)
    query_sql = 'select * from article where article_title=%s'
    sql = 'insert into article (article_title,article_author,article_content) values (%s, %s, %s)'
    # 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
    cursor = db.cursor()
    try:
        query_value = (article_title,)
        # 執(zhí)行 sql 語句
        cursor.execute(query_sql, query_value)
        results = cursor.fetchall()
        if len(results) == 0:
            value = (article_title, article_author, article_content)
            cursor.execute(sql, value)
            # 提交事務(wù)
            db.commit()
            print('--------------《%s》 insert table success-------------' % article_title)
            return True
        else:
            print('--------------《%s》 已經(jīng)存在-------------' % article_title)
            return False

    except BaseException as e:  # 如果發(fā)生錯誤則回滾
        db.rollback()
        print(e)

    finally:  # 關(guān)閉游標(biāo)連接
        cursor.close()
        # 關(guān)閉數(shù)據(jù)庫連接
        db.close()

定時設(shè)置

做了一個定時碉咆,過段時間就去爬一次抖韩。

import sched
import time


# 初始化 sched 模塊的 scheduler 類
# 第一個參數(shù)是一個可以返回時間戳的函數(shù),第二個參數(shù)可以在定時未到達(dá)之前阻塞疫铜。
schedule = sched.scheduler(time.time, time.sleep)


# 被周期性調(diào)度觸發(fā)的函數(shù)
def print_time(inc):
    # to do something
    print('to do something')
    schedule.enter(inc, 0, print_time, (inc,))


# 默認(rèn)參數(shù) 60 s
def start(inc=60):
    # enter四個參數(shù)分別為:間隔事件茂浮、優(yōu)先級(用于同時間到達(dá)的兩個事件同時執(zhí)行時定序)、被調(diào)用觸發(fā)的函數(shù)块攒,
    # 給該觸發(fā)函數(shù)的參數(shù)(tuple形式)
    schedule.enter(0, 0, print_time, (inc,))
    schedule.run()


if __name__ == '__main__':
    # 5 s 輸出一次
    start(5)

完整代碼

import pymysql
import requests
from bs4 import BeautifulSoup
import sched
import time


def create_table():
    # 建立連接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         db='python3learn')
    # 創(chuàng)建名為 article 數(shù)據(jù)庫語句
    sql = '''create table if not exists article (
    id int NOT NULL AUTO_INCREMENT, 
    article_title text,
    article_author text,
    article_content text,
    PRIMARY KEY (`id`)
    )'''
    # 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
    cursor = db.cursor()
    try:
        # 執(zhí)行 sql 語句
        cursor.execute(sql)
        # 提交事務(wù)
        db.commit()
        print('create table success')
    except BaseException as e:  # 如果發(fā)生錯誤則回滾
        db.rollback()
        print(e)

    finally:
        # 關(guān)閉游標(biāo)連接
        cursor.close()
        # 關(guān)閉數(shù)據(jù)庫連接
        db.close()


def insert_table(article_title, article_author, article_content):
    # 建立連接
    db = pymysql.connect(host='localhost',
                         user='root',
                         password='root',
                         db='python3learn',
                         charset="utf8")
    # 插入數(shù)據(jù)
    query_sql = 'select * from article where article_title=%s'
    sql = 'insert into article (article_title,article_author,article_content) values (%s, %s, %s)'
    # 使用 cursor() 方法創(chuàng)建一個游標(biāo)對象 cursor
    cursor = db.cursor()
    try:
        query_value = (article_title,)
        # 執(zhí)行 sql 語句
        cursor.execute(query_sql, query_value)
        results = cursor.fetchall()
        if len(results) == 0:
            value = (article_title, article_author, article_content)
            cursor.execute(sql, value)
            # 提交事務(wù)
            db.commit()
            print('--------------《%s》 insert table success-------------' % article_title)
            return True
        else:
            print('--------------《%s》 已經(jīng)存在-------------' % article_title)
            return False

    except BaseException as e:  # 如果發(fā)生錯誤則回滾
        db.rollback()
        print(e)

    finally:  # 關(guān)閉游標(biāo)連接
        cursor.close()
        # 關(guān)閉數(shù)據(jù)庫連接
        db.close()


def get_html_data():
    # get 請求
    response = requests.get('https://meiriyiwen.com/random')

    soup = BeautifulSoup(response.content, "html5lib")
    article = soup.find("div", id='article_show')
    article_title = article.h1.string
    print('article_title=%s' % article_title)
    article_author = article.find('p', class_="article_author").string
    print('article_author=%s' % article.find('p', class_="article_author").string)
    article_contents = article.find('div', class_="article_text").find_all('p')
    article_content = ''
    for content in article_contents:
        article_content = article_content + str(content)
        print('article_content=%s' % article_content)

    # 插入數(shù)據(jù)庫
    insert_table(article_title, article_author, article_content)


# 初始化 sched 模塊的 scheduler 類
# 第一個參數(shù)是一個可以返回時間戳的函數(shù)励稳,第二個參數(shù)可以在定時未到達(dá)之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)


# 被周期性調(diào)度觸發(fā)的函數(shù)
def print_time(inc):
    get_html_data()
    schedule.enter(inc, 0, print_time, (inc,))


# 默認(rèn)參數(shù) 60 s
def start(inc=60):
    # enter四個參數(shù)分別為:間隔事件囱井、優(yōu)先級(用于同時間到達(dá)的兩個事件同時執(zhí)行時定序)驹尼、被調(diào)用觸發(fā)的函數(shù),
    # 給該觸發(fā)函數(shù)的參數(shù)(tuple形式)
    schedule.enter(0, 0, print_time, (inc,))
    schedule.run()


if __name__ == '__main__':
    start(60*5)

問題:這只是對一篇文章爬蟲庞呕,如果是那種文章列表新翎,點擊是文章詳情,這種如何爬蟲解析住练?首先肯定要拿到列表地啰,再循環(huán)一個個解析文章詳情插入數(shù)據(jù)庫?還沒有想好該如何做更好讲逛,留給后面的課題吧亏吝。

最后

雖然我學(xué) Python 純屬業(yè)余愛好,但是也要學(xué)以致用盏混,不然這些知識很快就忘記了蔚鸥,期待下篇 Python 方面的文章。

參考

快速上手 — Requests 2.18.1 文檔

爬蟲入門系列(二):優(yōu)雅的HTTP庫requests

Beautiful Soup 4.2.0 文檔

爬蟲入門系列(四):HTML文本解析庫BeautifulSoup

公眾號

我的公眾號:吳小龍同學(xué)许赃,歡迎交流~


image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末止喷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子混聊,更是在濱河造成了極大的恐慌弹谁,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異预愤,居然都是意外死亡沟于,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門鳖粟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來社裆,“玉大人,你說我怎么就攤上這事向图∮拘悖” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵榄攀,是天一觀的道長嗜傅。 經(jīng)常有香客問我,道長檩赢,這世上最難降的妖魔是什么吕嘀? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮贞瞒,結(jié)果婚禮上偶房,老公的妹妹穿的比我還像新娘。我一直安慰自己军浆,他們只是感情好棕洋,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著乒融,像睡著了一般掰盘。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上赞季,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天愧捕,我揣著相機與錄音,去河邊找鬼申钩。 笑死次绘,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的撒遣。 我是一名探鬼主播断盛,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼愉舔!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起伙菜,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤轩缤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體火的,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡壶愤,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了馏鹤。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片征椒。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖湃累,靈堂內(nèi)的尸體忽然破棺而出勃救,到底是詐尸還是另有隱情,我是刑警寧澤治力,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布蒙秒,位于F島的核電站,受9級特大地震影響宵统,放射性物質(zhì)發(fā)生泄漏晕讲。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一马澈、第九天 我趴在偏房一處隱蔽的房頂上張望瓢省。 院中可真熱鬧,春花似錦痊班、人聲如沸勤婚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蛔六。三九已至,卻和暖如春废亭,著一層夾襖步出監(jiān)牢的瞬間国章,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工豆村, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留液兽,地道東北人。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓掌动,卻偏偏與公主長得像四啰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子粗恢,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容