標籤:因此 news 匯入 app jquer 返回 報錯 parent get
1,本節學習體會、心得 :
經過幾個月的努力學完了django。因此才選擇了這個爬蟲課程。經過第一章的學習,再次體會到了python的強大。之前一直為正則發愁,每次都要修改好幾次,才能匹配到。嚴重影響效率。然而,在這節中學到了新的技能 beautifulsoup4模組。用起來太爽了,簡直就像是在寫jquery 。大大提高了匹配的效率。
武老師講的非常通俗易懂,但是如果只聽的話,過後就忘了。在去寫已經學過的代碼,仍然不知道怎麼寫。但是照著筆記,舉一反三的去爬取幾個站之後。再來寫的話就可以拋棄筆記了。哈哈 ,也算是一點小心得了。
2,本節的知識點總結:
一、爬蟲入門
安裝requests模組 :pip3 install requests
安裝bs4 模組 :pip3 install beautifulstoup4
匯入request模組: import requests
匯入bs4模組 :from bst import BeautifulSoup
import requestsfrom bst import BeautifulSoup# 通過get方式擷取要爬取的頁面的內容 ret = requests.get(url=‘https://www.autohome.com.cn/news/‘)# 給擷取到的內容設定編碼 (apparent_encoding 擷取當前內容的編碼)ret.encoding = ret.apparent_encoding # 用beautifulsoup模組解析 擷取到的內容soup = ret.Beautifulsoup(ret.text,‘html.parser‘) #html.parser 是解析的方式 # find 找第一個對象 find_all 找到所有的對象 返回一個對象列表div = soup.find(name=‘div‘,id="auto-channel-lazyload-article")# div = soup.find(name=‘div‘,attrs=[‘id‘:"auto-channel-lazyload-article",‘class‘:‘btn‘])# div.text# div.attrs# div.get(‘href‘)# 擷取所有的li標籤對象 find_alllist = div.find_all(name=‘li‘)#list = div.find_all(name=‘li‘,_class=‘li‘)# list = div.find_all(name=‘li‘,attrs=[‘href‘:‘xxx.xxx.com‘])#遍曆list對象列表 列印出每個li下的h3標籤裡的內容 a標籤的href屬性值 p標籤的內容for i in list: h3 = i.find(name=‘h3‘) a = i.find(name=‘a‘) try: #由於h3的可能會是空 print會報錯 這裡可以用if判斷跳出迴圈 這裡我用try不讓它報錯 print(h3.text,a.get(‘href‘)) print(i.find(‘p‘).text) except: pass
入門知識到此結束
----------- end --------------
路飛學成-Python爬蟲實戰密訓-第1章