python爬蟲案例——根據網址爬取中文網站,獲取標題、子連線、子連線數目、連線描述、中文分詞列表
阿新 • • 發佈:2019-02-11
全棧工程師開發手冊 (作者:欒鵬)
其中使用到了urllib、BeautifulSoup爬蟲和結巴中文分詞的相關知識。
除錯環境python3.6
# 根據連線爬取中文網站,獲取標題、子連線、子連線數目、連線描述、中文分詞列表,
import urllib
from bs4 import BeautifulSoup
import bs4
import jieba #對中文進行分詞
# 分詞時忽略下列詞
ignorewords=[',','。','?','“','”','!',';',':','\n','、','-',',','.','?','\r\n','_' ,' ']
# 定義爬蟲類。獲取連結的題目、描述、分詞、深度
class crawler:
def __init__(self,url):
self.url = url
self.urls={}
self.urls[url]={
'num':1, #連線被引用的次數
'title':'', #連線的標題
'text':'', #連線的描述
'allword':[], #連線的所有分詞列表
}
def getword(self,soup):
# 獲取每個單詞
text=self.gettextonly(soup) #提取所有顯示出來的文字
words=self.separatewords(text) #使用分詞器進行分詞
allword=[]
for word in words:
if word not in ignorewords:
allword.append(word)
# print(allword)
return allword
# 根據一個網頁原始碼提取文字(不帶標籤的)。由外至內獲取文字元素。style和script內不要
def gettextonly(self,soup):
v=soup.string
if v==None:
c=soup.contents # 直接子節點的列表,將<tag>所有兒子節點存入列表
resulttext=''
for t in c:
if t.name=='style' or t.name=='script': #當元素為style和script和None時不獲取內容
continue
subtext=self.gettextonly(t)
resulttext+=subtext+'\n'
return resulttext
else:
if isinstance(v,bs4.element.Comment): #程式碼中的註釋不獲取
return ''
return v.strip()
# 利用正則表示式提取單詞(不能區分中文)。會將任何非字母非數字字元看做分隔符
def separatewords(self,text):
seg_list = jieba.cut(text, cut_all=False) #使用結巴進行中文分詞
return seg_list
# splitter=re.compile('\\W*')
# return [s.lower() for s in splitter.split(text) if s!='']
#爬蟲主函式
def crawl(self):
try:
response=urllib.request.urlopen(self.url)
except:
print("Could not open %s" % self.url)
return
try:
text = str(response.read(),encoding='utf-8')
soup=BeautifulSoup(text,'html.parser')
title = soup.title
self.urls[self.url]['title'] = title.get_text() # 將標題加入到屬性中
links=soup('a')
for link in links:
if ('href' in dict(link.attrs)):
newurl=urllib.parse.urljoin(self.url,link['href'])
if newurl.find("'")!=-1: continue
newurl=newurl.split('#')[0] # 去掉位置部分
if newurl[0:4]=='http':
if newurl not in self.urls:
linkText = self.gettextonly(link) #獲取連線的描述
self.urls[newurl]={
'num':1, #連線被引用的次數
'text':linkText #連結描述
}
else:
self.urls[newurl]['num']+=1 #連線數+1,這裡有演算法只算一次
allword = self.getword(soup.body) # 獲取分詞
self.urls[self.url]['allword'] = allword # 將分詞加入到屬性中
except:
print("Could not parse page %s" % self.url)
if __name__ == '__main__':
url='http://blog.csdn.net/luanpeng825485697/article/details/78378653'
mycrawler = crawler(url)
mycrawler.crawl()
print(mycrawler.urls[url]['allword'])