BeautifulSoup技術爬取豆瓣TOP250

2021-10-11 13:24:54 字數 1379 閱讀 3538

1.環境:vs2019

2.首先安裝re, beautifulsoup,codecs,requests庫,可以用 pip安裝

功能:將top250的電影名,評分,評價人數,鏈結,影評獲取下來並生成.html檔案效果如圖:

先展示爬蟲函式:

def pachong(url):

cc = requests.get(url,headers=headers)

cc=cc.text

cc = beautifulsoup(cc,"html.parser")

print(u'豆瓣top250 \n')

for tag in cc.find_all(attrs=):

shu = tag.find('em').get_text() #序號

print (shu)

outf.write(u""+ shu)

name = tag.find_all(attrs=) #中文名稱

zname = name[0].get_text()

print (u'[名稱]',zname)

outf.write(u"

"+ zname)

urlm = tag.find(attrs=).a #鏈結

urls = urlm.attrs['href']

print (u'[鏈結]',urls)

outf.write(u"

"+urls)

ping = ping.replace('\n',' ')

ping = ping.lstrip()

mode = re.compile(r'\d+\.?\d*')

mm = mode.findall(ping)

k=0for n in mm:

if k==0:

print (u"[分數]"+n)

outf.write(u"

" + n)

elif k==1:

outf.write(u"

" +n)

k=k+1

yu = tag.find(attrs=) #評語

if(yu):

content = yu.get_text()

print (u'[評語]',content)

outf.write(u"

") outf.write(content)

outf.write(u"

"+"\n")

注意:1.爬取豆瓣網時需要有請求頭

2.此處用的beautifsoup技術進行爬取

3.寫入的檔案的是.html所以有

等寫入檔案,這是.html語言

BeautifulSoup常用方法

1.初始化 2.查詢指定標籤 eg 要找到符合的所有標籤 p.findall div 反覆利用標籤特徵可以找到最終需要的標籤 3.直接加標籤名可以找到所有子標籤 eg 找到所有標籤 p.td 4.直接以字典形式,可以訪問標籤內對應屬性的值 eg 要找到 中href 的值 www.csdn.net p...

BeautifulSoup學習筆記

prettify 將html 格式化 get text 獲得所有文字內容 contens 返回所有子節點 children 返回子節點生成器 descendants 返回所有子孫節點的生成器 strings 返回包含的多個字串的生成器 stripped strings 返回包含的多個字串 去除多餘空...

爬蟲 BeautifulSoup 模組

二 根據這個dom樹就可以按照節點的名稱 屬性和文字搜尋節點 find all 方法會搜尋出所有滿足要求的節點,find 方法只會搜尋出第乙個滿足要求的節點 兩個方法的引數一模一樣 三 得到節點以後,就可以訪問它的名稱 屬性 文字。a為標籤名稱 超連結 href,class為屬性,顯示在頁面上的是p...