python百度贴吧爬虫总体设计_零基础Python爬虫实现(百度贴吧)

提示:本学习来自Ehco前辈的文章, 经过实现得出的笔记。

目标

http://tieba.baidu.com/f?kw=linux&ie=utf-8

网站结构

学习目标

由于是第一个实验性质爬虫,我们要做的不多,我们需要做的就是:

1. 从网上爬下特定页码的网页

2. 对于爬下的页面内容进行简单的筛选分析

3. 找到每一篇帖子的 标题、发帖人、日期、楼层、以及跳转链接

4. 将结果保存到文本。

发现规律

&pn=0 : 首页

&pn=50: 第二页

&pn=100:第三页

&pn=50*n 第n页

50 表示 每一页都有50篇帖子。

这样就能实现翻页操作

附上代码

import requests

import time

from bs4 import BeautifulSoup

def get_html(url):

try:

r = requests.get(url, timeout=30)

r.raise_for_status()

r.encoding = 'utf-8'

return r.text

except:

return "error"

def get_content(url):

comments = []

html = get_html(url)

soup = BeautifulSoup(html, 'lxml')

liTags = soup.find_all('li', attrs={'class':' j_thread_list clearfix'})

for li in liTags:

comment = {}

try:

#标题

comment['title'] = li.find(

'a', attrs={'class':'j_th_tit '}).text.strip()

#链接

comment['link'] = "http://tieba.baidu.com/" + \

li.find('a', attrs={'class' : 'j_th_tit'})['href']

#发帖人

comment['name'] = li.find(

'span', attrs = {'class':'tb_icon_author '}

).text.strip()

#发帖时间

comment['time'] = li.find(

'span', attrs={'class':'pull-right is_show_create_time'}

).text.strip()

#回复数量

comment['replyNum'] = li.find(

'span', attrs={'class':'threadlist_rep_num center_text'}

).text.strip()

comments.append(comment)

except:

print("出了点小问题")

return comments

def Out2File(dict):

with open('TTBT.txt', 'a+') as f:

for comment in dict:

f.write('标题: {} \t 连接: {} \t 发帖人: {} \t 发帖时间: {} \t 回复数量: {} \n'.format(

comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']

))

print("当前页面爬取完成")

def main(base_url, deep):

url_list = []

for i in range(0, deep):

url_list.append(base_url + '&pn' + str(50 * i))

print("所有的网页已经下载到本地! 开始筛选信息")

for url in url_list:

content = get_content(url)

Out2File(content)

print("所有的信息都已经保存完毕")

base_url = 'http://tieba.baidu.com/f?kw=linux&ie=utf-8'

deep = 3

if __name__ == '__main__':

main(base_url, deep)

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值