1. 程式人生 > >簡單爬蟲項目實戰(一)

簡單爬蟲項目實戰(一)

int htm val target 組類型 resp inf 內容 爬蟲

概述

  最近自己想搞一個小的項目,這個項目我們就先從爬蟲開始,爬取直播吧的NBA滾動新聞,再存入數據庫。先寫個簡單點的,後期再不斷的優化下。

準備

  直播吧對於喜歡看球的朋友肯定不陌生,https://www.zhibo8.cc/,打開我們看到如下界面,

技術分享圖片

我們選擇NBA新聞tab,然後選擇滾動新聞,

技術分享圖片

我們按下F12,分析下這個請求

技術分享圖片

我們試著來直接請求下這個地址

技術分享圖片

哈哈,太好了,這個就是頁面上的內容啊,我們就要解析這個數據,就能得到所有數據,是不是很簡單呢

代碼

    conn = pymysql.connect("localhost", "root", "123456", "news")  # 獲取連接
    cursor = conn.cursor()  # 獲取遊標 默認元組類型
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    insert_news_sql = ‘insert into news(title, url, hash, publish_time, news_type, from_name) values(%s, %s, %s, %s, %s, %s)‘

    response = requests.get("https://m.zhibo8.cc/json/hot/24hours.htm")
    news_list = json.loads(response.text).get(‘news‘)
    news_data = ()
    for news in news_list:
        title = news.get(‘title‘)
        news_type = news.get(‘type‘)
        publish_time = news.get(‘createtime‘)
        url = news.get(‘from_url‘)
        from_name = news.get(‘from_name‘)
        hash_str = hash(title)
        news_data = (title, url, hash_str, publish_time, news_type, from_name)
        cursor.execute(insert_news_sql, news_data)  # 執行語句

    conn.commit()  # 提交
    cursor.close()  # 關閉遊標
    conn.close()  # 關閉連接

技術分享圖片  

簡單爬蟲項目實戰(一)