python实现百度贴吧爬虫

本文利用BeautifulSoup,实现了百度贴吧爬虫,可以爬取所有帖子的每一页。

  • page_analyse(content) 定义了每个帖子你所需要爬取的逻辑,在这里是匹配所有《XXX》类型的字符串。
  • page_traverse函数是负责给每个帖子翻页,自动获取总页数,并将页面的内容传递给page_analyse进行分析。
import urllib.request
from bs4 import BeautifulSoup
import re
word_dict = {}
def page_analyse(content):
    p = re.compile(r'《.*?》')
    words = p.findall(content.decode('utf8','ignore')) #得到的所有书名的列表
    for w in words:
        if w not in word_dict:
            word_dict[w] = 1
        else:
            word_dict[w] = word_dict[w] + 1
    #print(word_dict)

def page_traverse(link):
    content = urllib.request.urlopen(link).read()
    page_analyse(content)
    soup = BeautifulSoup(content)
    items=soup.select("span.red")
    item=items[1]
    num_page=int(list(filter(lambda x:x.isdigit(),item))[0]) #帖子的总页数
    for i in range(2,num_page):
        content = urllib.request.urlopen(link+'?pn='+str(i)).read()
        page_analyse(content)

for pn in range(0,151,50):
    content = urllib.request.urlopen('http://tieba.baidu.com/f?kw=%E4%B9%A6%E8%8D%92&ie=utf-8&tab=good&cid=7&pn='+str(pn)).read() #男频推荐 pn=0 50 100 150
    soup = BeautifulSoup(content)
    items=soup.select("a.j_th_tit")
    for item in items:
        link='http://tieba.baidu.com'
        link+=BeautifulSoup(str(item)).a['href']#得到每个帖子的链接
        page_traverse(link)

f=open('data.csv','w')
for key, value in word_dict.items():
    f.write('"'+key+'",'+ str(value)+"\n")
f.close()
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值