Python爬取新浪微博評論數據,寫入csv文件中

由於新浪微博網頁版爬蟲比較困難,故採起用手機網頁端爬取的方式html

操做步驟以下:json

1. 網頁版登錄新浪微博api

2.打開m.weibo.cncookie

3.查找本身感興趣的話題,獲取對應的數據接口連接post

4.獲取cookies和headersurl

 

# -*- coding: utf-8 -*-
import requests
import csv
import os


base_url = 'https://m.weibo.cn/api/comments/show?id=4131150395559419&page={page}'
cookies = {'Cookie':'xxx'} 
headers = {'User-Agent':'xxx'}

path = os.getcwd()+"/weibo.csv"
csvfile = open(path, 'a+', encoding='utf-8',newline='')
writer = csv.writer(csvfile)
writer.writerow(('username','source','comment'))

for i in range(0,83):
    try:
        url = base_url.format(page=i)
        resp = requests.get(url, headers=headers, cookies=cookies)
        jsondata = resp.json()

        data = jsondata.get('data')
        for d in data:
            created_at = d.get("created_at")
            source = d.get("source")
            username = d.get("user").get("screen_name")
            comment = d.get("text")
            print((username,source,comment))
            writer.writerow((username, source, comment))
    except:
        print('*'*1000)
        pass

csvfile.close()

 

至於爬出來的數據有非中文的數據,要提取中文請參考:篩選出一段文字中的中文spa

 

未完待續。。。。code

相關文章
相關標籤/搜索