# -*- coding: utf-8 -*-
import requests
import re
‘’’
(‘J-Dub’, ‘小吧主’, ‘13’, ‘有的人天之骄子,从选秀便是球队核心有的人甘作绿叶,一心一意干好自己的事有的人能力有限,最后只能被联盟淘汰而有的人
虽有天赋,但是球队的处境让他无法让他的天赋得到兑现,而他们可能在离开球队后,便得到突猛进的发展,可能在同位置球员离开后成为球队老大。今天楼主就来和大家谈谈那些从角色球员最终成为球队老大的球员。’, ‘来自’, ‘iPhone客户端’, ‘1楼’, ‘2016-05-17 19:22’)
‘’’
url = 'https://tieba.baidu.com/p/4553108519'
html = requests.get(url).content
rs = re.findall(re.compile(r'<li class="d_name.*?<a.*?>(.*?)</a>.*?<div class="d_badge_tit.*?>(.*?)</div>.*?lv">(.*?)</div>.*?<cc.*?>(.*?)</cc>.*?<span class="tail-info.*?>(.*?)<a.*?>(.*?)</a>.*?<span.*?>(.*?)</sp.*?<span class="tail.*?>(.*?)</span>',re.S), html)
找到帖子名称
pattern = re.compile(r'<title>(.*?)</title>')
tz_rs = re.search(pattern, html)
tz_name = tz_rs.group(1)
file_name = tz_name+'.txt'
1.打开文件 decode('utf-8) 使用utf-8解码,得到就是正常的中文
file_handle = open(file_name.decode('utf-8'),'w')
遍历每一个楼层的数据
for floor in rs:
name = floor[0]
# 去除name中的img标签
replace_img = re.compile(r'<img.*?>')
name = re.sub(replace_img, '-', name)
# 取出头衔
rank = floor[1]
# 取出等级
level = floor[2]
# 把内容中的<br>替换为\n
content = floor[3].replace('<br>','\n')
# 把内容中的标签全部剔除,并且去除空格
strip_ele = re.compile(r'<.*?>',re.S)
content = re.sub(strip_ele, '', content).strip()
# 取出来自客户端...
from_device = floor[4]+floor[5]
if 'tail' in from_device:
# 取出楼层的正则
floor_pat = re.compile('\w+楼')
rs = re.search(floor_pat, from_device)
floor_num = rs.group()
# 取出日期的正则
datetime_pat = re.compile('<span class="tail.*?>(.*?)</span>')
rs = re.search(datetime_pat, from_device)
datetime = rs.group(1)
from_device = '来自PC电脑版'
else:
# 取出楼层
floor_num = floor[6]
# 取出日期
datetime = floor[7]
# 写入
file_handle.write('层主姓名:%s 等级:%s 头衔:%s\n'%(name, level, rank))
file_handle.write(content)
file_handle.write('\n')
file_handle.write('%s 楼层:%s 日期:%s\n'%(from_device, floor_num, datetime))
file_handle.write('****************************************\n')
file_handle.close()