# -*-coding:utf-8-*-
"""
获取百度贴吧:潍坊学院的基本内容
爬虫线路:requests - bs4
Python版本:3.5
1. 从网上爬下特定页码的网页
2. 对于爬下的页面内容进行简单的筛选分析
3. 找到每一篇帖子的 标题、发帖人、日期、楼层、以及跳转链接
4. 将结果保存到文本
"""
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 = r.apparent_encoding.
r.encoding = 'utf-8'
return r.text
except:
return '网络连接异常'
# 分析贴吧的网页文件,整理信息,保存在列表变量中
def get_content(url):
# 保存所有帖子信息
comments = []
# 获取网址
html = get_html(url)
# 熬汤
soup = BeautifulSoup(html, 'lxml')
# 获取li标签的列表
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 '})['title']
comment['link'] = "http://tieba.baidu.com/" + \
li.find('a', attrs={'class': 'j_th_tit '})['href']
comment['name'] = li.find('a', attrs={'class': 'frs-author-name j_user_card '}).string
comment['time'] = li.find('span', attrs={'class': 'pull-right is_show_create_time'}).string
comment['replyNum'] = li.find(
'span', attrs={'class': 'threadlist_rep_num center_text'}).string
comments.append(comment)
except:
print('找不到相关文章信息')
return comments
# 将结果保存到本地
def Out2File(dict):
# 打开文件,使用追加模式
with open('D:\BDTB.txt', 'a+', encoding='utf-8') 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 = []
# 将需要爬取的url存入列表
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?ie=utf-8&kw=%E6%BD%8D%E5%9D%8A%E5%AD%A6%E9%99%A2&fr=search'
# 设置需要爬取的页码数量
deep = 5272
if __name__ == '__main__':
main(base_url, deep)