10、實戰(zhàn)2:爬取微博內(nèi)容

附源碼:

from urllib.parse import urlencode

import requests

from pyquery import PyQuery as pq

base_url = 'https://m.weibo.cn/api/container/getIndex?'

headers = {

? ? 'Host': 'm.weibo.cn',

? ? 'Referer': 'https://m.weibo.cn/u/3519635132',

? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',

? ? 'X-Requested-With': 'XMLHttpRequest'

}

max_page = 2

def get_page(page):

? ? params = {

? ? ? ? 'type': 'uid',

? ? ? ? 'value': '3519635132',

? ? ? ? 'containerid': '1076033519635132',

? ? ? ? 'page': page

? ? }

? ? url = base_url + urlencode(params)

? ? try:

? ? ? ? response = requests.get(url, headers=headers)

? ? ? ? if response.status_code == 200:

? ? ? ? ? ? return response.json(), page

? ? except requests.ConnectionError as e:

? ? ? ? print('Error', e.args)

def parse_page(json, page: int):

? ? if json:

? ? ? ? items = json.get('data').get('cards')

? ? ? ? for index, item in enumerate(items):

? ? ? ? ? ? if page == 1 and index == 1:

? ? ? ? ? ? ? ? continue

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? item = item.get('mblog', {})

? ? ? ? ? ? ? ? weibo = {}

? ? ? ? ? ? ? ? weibo['id'] = item.get('id')

? ? ? ? ? ? ? ? #提取文本信息需要注意使用方法

? ? ? ? ? ? ? ? weibo['text'] = pq(item.get('text')).text()

? ? ? ? ? ? ? ? weibo['attitudes'] = item.get('attitudes_count')#點贊數(shù)量

? ? ? ? ? ? ? ? weibo['comments'] = item.get('comments_count')#評論數(shù)量

? ? ? ? ? ? ? ? weibo['reposts'] = item.get('reposts_count')#轉(zhuǎn)發(fā)數(shù)量

? ? ? ? ? ? ? ? yield weibo

if __name__ == '__main__':

? ? for page in range(1, max_page + 1):

? ? ? ? json = get_page(page)

? ? ? ? results = parse_page(*json)

? ? ? ? for result in results:

? ? ? ? ? ? print(result)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容