您好,登錄后才能下訂單哦!
本篇內容介紹了“怎么用python抓取百度貼吧內容”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
# -*- coding: utf-8
import urllib2
import urllib
import re,os
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Tiebar:
#初始化數據
def __init__(self,base_url,see_lz):
self.base_url = base_url
self.see_lz = '?see_lz=' + see_lz
self.page = 1
self.user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
self.headers = { 'User-Agent' : self.user_agent }
self.tool = Tool()
self.out_put_file = 'd:/python/test/out.txt'
#獲取頁面內容的方法
def get_cotent(self,page):
try:
url = self.base_url + self.see_lz + '&pn=' + str(page)
request = urllib2.Request(url,headers=self.headers)
response = urllib2.urlopen(request)
act_url = response.geturl()
print 'init url=',url,'act url=',act_url
if url == act_url:
content = response.read()
return content
else:
return None
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u"連接貼吧頁面失敗,錯誤原因",e.reason
return None
#獲取帖子主題
def get_titile(self):
content = self.get_cotent(1)
pattern = re.compile('<h4 .*?>(.*?)</h4>')
result = re.search(pattern,content)
if result:
return result.group(1).strip()
else:
return None
#獲取帖子的頁數
def get_page_num(self):
content = self.get_cotent(1)
pattern = re.compile('<li class="l_reply_num.*?.*?<span.*?>(.*?)',re.S)
result = re.search(pattern,content)
if result:
return result.group(1).strip()
else:
return None
#獲取帖子內容
def get_tiebar(self,page):
content = self.get_cotent(page).decode('utf-8')
str = ''
if not content:
print "抓取完畢"
return None
patt_content = re.compile('<a data-field=.*?class="p_author_name j_user_card".*?>(.*?)</a>.*?'
+ '<div id=".*?" class="d_post_content j_d_post_content "> '
+ '(.*?)',re.S)
msg = re.findall(patt_content,content)
for item in msg:
str = str + '\n作者-----' + item[0] + '\n' + '帖子內容-----' + item[1].strip() + '\n'
str = self.tool.replace(str)
# print u'作者',item[0],u'帖子內容:',item[1]
return str
#寫文件
def writeStr2File(self,out_put_file,str1,append = 'a'):
# 去掉文件,保留路徑。比如 'a/b/c/d.txt' 經過下面代碼會變成 'a/b/c'
subPath = out_put_file[:out_put_file.rfind('/')]
# 如果給定的路徑中,文件夾不存在,則創建
if not os.path.exists(subPath):
os.makedirs(subPath)
# 打開文件并將 str 內容寫入給定的文件
with open(out_put_file, append) as f:
f.write(str1.strip()+'\n')
def start_crawl(self):
page_num = self.get_page_num()
if page_num == None:
print "url已失效,請重試!"
return
print u"該帖子共有" + str(page_num) + u"頁數據"
for i in range(1,int(page_num)+1):
print u"正在寫入第" + str(i) + u"頁數據..."
content = "正在寫入第" + str(i) + u"頁數據------------------------------------\n" + self.get_tiebar(i)
self.writeStr2File(self.out_put_file,content)
class Tool:
#去除img標簽
patt_img = re.compile(r'<img.*?>')
patt_herf = re.compile(r'<a.*?>|</a>')
patt_br = re.compile(r'<br>{1,3}')
def replace(self,content):
content = re.sub(self.patt_img,"",content)
content = re.sub(self.patt_herf,"",content)
content = re.sub(self.patt_br,"\n",content)
return content.strip()
tiebar = Tiebar('http://tieba.baidu.com/p/3138733512','1')
# title = tiebar.get_titile()
# page_num = tiebar.get_page_num()
# print title,page_num
tiebar.start_crawl()
“怎么用python抓取百度貼吧內容”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。