用python爬取贴吧数据
有时会逛贴吧,看故事,看别人侃大山,
但是一页一页翻费劲啊;
又没有按回复量排序的功能(实验功能根本不能用!),_…
这促使我写了个python爬虫,爬取点击量超过某个阈值的帖子。
自身需求绝对是学习的第一动力。
虽然代码量不大,但有效地解决了问题,
看到成果出来,心中好像有泉水汩汩涌出~

实现思路很简单,
用python模拟浏览器发送get请求,
从返回的信息中提取点击量高的帖子,
以上两步循环若干次,
再将最终结果转为pandas对象,
然后可以导出到Excel,
就完成啦~
用到的python包有requests,BeautifulSoup,pandas,官网有详细用例。
代码如下:
import time
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
M = 3000
template_url = "https://tieba.baidu.com/f?kw=%E5%BF%83%E7%90%86%E5%AD%A6&ie=utf-8&pn={}"
{ }为占位符,方便发送不同页面(第n页)的请求。
def extra_from_one_page(page_lst):
'''从一页中提取 帖子'''
tmp = []
for i in page_lst:
if int(i.find(class_='threadlist_rep_num').text) > M:
dic = {}
dic['num'] = int(i.find(class_='threadlist_rep_num').text)
dic['name'] = i.find(class_='threadlist_title').text
dic['address'] = 'https://tieba.baidu.com' + i.find(class_='threadlist_title').a['href']
tmp.append(dic)
return tmp
以上 class name 是基于对贴吧html页面结构的观察而定的。(方法:在浏览器中打开控制台仔细观察)
def search_n_pages(n):
'''爬取n页数据'''
target = []
for i in range(n):
print('page:', i)
target_url = template_url.format(50*i)
res = requests.get(target_url)
soup = BeautifulSoup(res.text, 'html.parser')
page_lst = soup.find_all(class_='j_thread_list')
target.extend(extra_from_one_page(page_lst))
time.sleep(0.2)
return target
功能主体实现完毕,下面以十分活跃的心理学吧为例,进行展示。
d = search_n_pages(200)
我电脑的运行时间:
CPU times: user 40.4 s, sys: 496 ms, total: 40.9 s
Wall time: 5min 5s
data = pd.DataFrame(d)
data.to_excel('心理学-贴吧.xlsx')

得到结果之后就可以想个哪个点哪个了,节省了很多人工检索的时间~ |