使用python简单爬取数据
爬取中北大学百度贴吧的数据并将其存储在文本文件中
import html
import os
import urllib.request
import time
from bs4 import BeautifulSoup
# 爬取数据初始化
print("***开始爬取数据***")
url = "http://tieba.baidu.com/f?kw=%E4%B8%AD%E5%8C%97%E5%A4%A7%E5%AD%A6&ie=utf-8"
#读取网页
html = urllib.request.urlopen(url).read()
# 创建BeautifulSoup对象
soup = BeautifulSoup(html, "lxml")
# 开始爬取数据
# 创建并打开文件夹
start_time = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime())
f = open('ZBtb-' + start_time + '.txt', 'a+',encoding='utf-8')
f.write('爬取时间' + start_time + '\n')
# 获取数据并写入到文本文件
# 寻找标签是a,类名class是j_th_tit的节点
all = soup.find_all("a",{'class':'j_th_tit'})
title = str(all).split('</a>')
# title = list(ALL)
title.pop()
i = 0
for j in title:
i += 1
each = j.split('title="')[1]
f.write('【标题 ' + str(i)+'】' + each + '\n')
f.close()
print("**爬取数据结束**")
-
该代码获取的数据存储的文本文件在当前项目下
-
程序运行截图