零基础写python爬虫之抓取百度贴吧代码分享

WBOY
Release: 2016-06-06 11:20:45
Original
2596 people have browsed it

这里就不给大家废话了,直接上代码,代码的解释都在注释里面,看不懂的也别来问我,好好学学基础知识去!

代码如下:


# -*- coding: utf-8 -*-
#---------------------------------------
#   程序:百度贴吧爬虫
#   版本:0.1
#   作者:why
#   日期:2013-05-14
#   语言:Python 2.7
#   操作:输入带分页的地址,去掉最后面的数字,设置一下起始页数和终点页数。
#   功能:下载对应页码内的所有页面并存储为html文件。
#---------------------------------------
import string, urllib2
#定义百度函数
def baidu_tieba(url,begin_page,end_page):  
    for i in range(begin_page, end_page+1):
        sName = string.zfill(i,5) + '.html'#自动填充成六位的文件名
        print '正在下载第' + str(i) + '个网页,并将其存储为' + sName + '......'
        f = open(sName,'w+')
        m = urllib2.urlopen(url + str(i)).read()
        f.write(m)
        f.close()
#-------- 在这里输入参数 ------------------
# 这个是山东大学的百度贴吧中某一个帖子的地址
#bdurl = 'http://tieba.baidu.com/p/2296017831?pn='
#iPostBegin = 1
#iPostEnd = 10

bdurl = str(raw_input(u'请输入贴吧的地址,去掉pn=后面的数字:\n'))
begin_page = int(raw_input(u'请输入开始的页数:\n'))
end_page = int(raw_input(u'请输入终点的页数:\n'))
#-------- 在这里输入参数 ------------------
#调用
baidu_tieba(bdurl,begin_page,end_page)

以上就是python抓取百度贴吧的一段简单的代码,非常的实用吧,各位可以自行扩展下。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!