1. 程式人生 > 其它 >不會吧,學過爬蟲連這個網站都爬不了?那Python豈不是白學了

不會吧,學過爬蟲連這個網站都爬不了?那Python豈不是白學了

本文內容

  1. 系統分析目標網頁
  2. html標籤資料解析方法
  3. 海量圖片資料一鍵儲存

環境介紹

  • python 3.8
  • pycharm

模組使用

  • requests >>> pip install requests
  • parsel >>> pip install parsel
  • time 時間模組 記錄執行時間

通用爬蟲

匯入模組

import requests  # 資料請求模組 第三方模組 pip install requests
import parsel  # 資料解析模組 第三方模組 pip install parsel
import
re # 正則表示式模組

請求資料

url = f'https://fabiaoqing.com/biaoqing/lists/page/{page}html'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
}
response = requests.get(url=url, headers=headers)
# <Response [200]> response 物件 200狀態碼 表示請求成功

解析資料

解析速度 bs4 解析速度會慢一些,如果你想要對於字串資料內容,直接取值,只能正則表示式

selector = parsel.Selector(response.text) # 把獲取下來html字串資料內容 轉成 selector 物件
title_list = selector.css('.ui.image.lazy::attr(title)').getall()
img_list = selector.css('.ui.image.lazy::attr(data-original)').getall()
# 把獲取下來的這兩個列表 提取裡面元素 一一提取出來
# 提取列表元素 for迴圈 遍歷 for title, img_url in zip(title_list, img_list): title = re.sub(r'[\/:*?"<>|\n]', '_', title) # 名字太長 報錯 img_name = img_url.split('.')[-1] # 通過split() 字串分割的方法 根據列表索引位置取值 img_content = requests.get(url=img_url).content # 獲取圖片的二進位制資料內容

儲存資料

with open('img\\' + title + '.' + img_name, mode='wb') as f:
    f.write(img_content)
print(title)

共耗時:61秒

多執行緒爬蟲

傳送求情

def get_response(html_url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
    }
    response = requests.get(url=html_url, headers=headers)
    return response

獲取圖片url地址,以及圖片名字

def get_img_info(html_url):
    response = get_response(html_url)
    selector = parsel.Selector(response.text)  # 把獲取下來html字串資料內容 轉成 selector 物件
    title_list = selector.css('.ui.image.lazy::attr(title)').getall()
    img_list = selector.css('.ui.image.lazy::attr(data-original)').getall()
    zip_data = zip(title_list, img_list)
    return zip_data

儲存資料

def save(title, img_url):
    title = re.sub(r'[\/:*?"<>|\n]', '_', title)
    # 名字太長 報錯
    img_name = img_url.split('.')[-1]  # 通過split() 字串分割的方法 根據列表索引位置取值
    img_content = requests.get(url=img_url).content  # 獲取圖片的二進位制資料內容
    with open('img\\' + title + '.' + img_name, mode='wb') as f:
        f.write(img_content)
    print(title)

主函式

def main(html_url):
    zip_data = get_img_info(html_url)
    for title, img_url in zip_data:
        save(title, img_url)

入口

if __name__ == '__main__':
    start_time = time.time()
    exe = concurrent.futures.ThreadPoolExecutor(max_workers=10)
    for page in range(1, 11):
        url = f'https://fabiaoqing.com/biaoqing/lists/page/{page}html'
        exe.submit(main, url)
    exe.shutdown()
    end_time = time.time()
    use_time = int(end_time - start_time)
    print('程式耗時: ', use_time)

共耗時:19秒

對於本篇文章有疑問的同學可以加【資料白嫖、解答交流群:1039649593】