天天看点

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] = 
        else:
            word_dict[w] = word_dict[w] + 
    #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[]
    num_page=int(list(filter(lambda x:x.isdigit(),item))[]) #帖子的总页数
    for i in range(,num_page):
        content = urllib.request.urlopen(link+'?pn='+str(i)).read()
        page_analyse(content)

for pn in range(,,):
    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()