1. 程式人生 > >python爬取新浪財經的股票資訊

python爬取新浪財經的股票資訊

import requests
import threading

def display_info(code):
    url = 'http://hq.sinajs.cn/list=' + code
    response = requests.get(url).text
    print(response)

def single_thread(codes):
    for code in codes:
        code = code.strip()
        display_info(code)

def multi_thread(tasks):
    # 用列表推導生成執行緒,注意codes後面的‘,’!
    threads = [threading.Thread(target = single_thread, args = (codes,)) for codes in tasks]
    # 啟動執行緒
    for t in threads:
        t.start()
    # 等待執行緒結束
    for t in threads:
        t.join()

# 注意main函式的形式
if __name__ == '__main__':
    codes = ['sh600519', 'sh601006', 'sh603277', 'sh601012', 'sh600340', 'sh600026']
    # 計算每個執行緒要做多少工作
    thread_len = int(len(codes) / 4)
    t1 = codes[0: thread_len]
    t2 = codes[thread_len: thread_len * 2]
    t3 = codes[thread_len * 2: thread_len * 3]
    t4 = codes[thread_len * 3:]

    # 多執行緒啟動
    multi_thread([t1, t2, t3, t4])


用新浪財經爬取股票資訊,注意事項:輸入的股票程式碼要真實,否則程式碼可以執行,但是沒有結果(我開始很納悶,除錯了半天,發現600001沒有股票)