天天看點

Python爬蟲執行個體:爬取豆瓣Top250 Python爬蟲執行個體:爬取貓眼電影——破解字型反爬Python爬蟲執行個體:爬取B站《工作細胞》短評——異步加載資訊的爬取

python3 爬蟲入門級示例,附源碼。

入門第一個爬蟲一般都是爬這個,實在是太簡單。用了 requests 和 bs4 庫。

1、檢查網頁元素,提取所需要的資訊并儲存。這個用 bs4 就可以,前面的文章中已經有詳細的用法闡述。

2、找到下一個 url 位址。本例中有兩種方法,一是通過 url 的規則,本例中通過比較發現,隻要更改 url 中的 start 參數值就可以;二是通過下一個頁的标簽擷取下一頁的 url。代碼中采用了第一種方法。

3、判斷退出條件,爬蟲不可能無限制循環下去。

在這個最簡單的示例中,實作以上三步一個爬蟲就完成了。簡單到不想做其他說明,直接看代碼吧。

"""
爬取豆瓣電影Top250
"""

import os
import re
import time
import requests
from bs4 import BeautifulSoup


def download(url, page):
    print(f"正在爬取:{url}")
    html = requests.get(url).text   # 這裡不加text傳回<Response [200]>
    soup = BeautifulSoup(html, \'html.parser\')
    lis = soup.select("ol li")
    for li in lis:
        index = li.find(\'em\').text
        title = li.find(\'span\', class_=\'title\').text
        rating = li.find(\'span\', class_=\'rating_num\').text
        strInfo = re.search("(?<=<br/>).*?(?=<)", str(li.select_one(".bd p")), re.S | re.M).group().strip()
        infos = strInfo.split(\'/\')
        year = infos[0].strip()
        area = infos[1].strip()
        type = infos[2].strip()
        write_fo_file(index, title, rating, year, area, type)
    page += 25
    if page < 250:
        time.sleep(2)
        download(f"https://movie.douban.com/top250?start={page}&filter=", page)


def write_fo_file(index, title, rating, year, area, type):
    f = open(\'movie_top250.csv\', \'a\')
    f.write(f\'{index},{title},{rating},{year},{area},{type}\n\')
    f.closed


def main():
    if os.path.exists(\'movie_top250.csv\'):
        os.remove(\'movie_top250.csv\')

    url = \'https://movie.douban.com/top250\'
    download(url, 0)
    print("爬取完畢。")


if __name__ == \'__main__\':
    main()      

相關博文推薦: