視頻重點####
練習代碼####
總結#####
1. 視頻重點###
解析網(wǎng)頁soup = Beautifulsoup(
'html','lxml')Beautifulsoup只認css selector的寫法xpatch是表示元素絕對路徑的方法描述要爬取元素的位置select到了一類信息放入了列表,之后要for循環(huán)釋放這些位置信息
釋放爬取標簽的信息
get_text()方法能獲取標簽中的文本信息,get()方法來獲得標簽中的屬性信息,比如<img src='#'>中的鏈接信息。用zip()函數(shù)搭配for循環(huán),將所有信息裝入字典中。stripped_string獲取父節(jié)點下所有子節(jié)點的文本信息。
2. 練習代碼###
from bs4 import BeautifulSoup
with open('F:/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/index.html','r') as wb_data:
soup = BeautifulSoup(wb_data,'lxml')
imgs = soup.select('body > div > div > div.col-md-9 > div > div > div > img')
titles = soup.select('body > div > div > div.col-md-9 > div > div > div > div.caption > h4 > a ')
prices = soup.select('body > div > div > div.col-md-9 > div > div > div > div.caption > h4.pull-right')
rates1=soup.find_all('span', class_='glyphicon') #find_all()方法,class因為是關鍵字,在使用css selector時用class_
views=soup.select('body > div > div > div.col-md-9 > div > div > div > div.ratings > p.pull-right')
rates= rates1[2:]。#rates1列表中前兩個不是星級,去掉前兩個存到rates列表中。
str_rates=[] #創(chuàng)建了一個存放將rates元素字符串化后的列表,因為在之后使用list.count()是,元素包含關鍵字。
stars=[]#存放一個商品星級的列表
nums=[]
for i in rates:#此迭代將元素字符串化
str_rates.append(str(i))
while len(str_rates)!=0:#此循環(huán)借鑒課程的參考,del 選出的五個元素,配合while循環(huán),將全部星級按五個一組分好,list.count()統(tǒng)計實心星的個數(shù)。
stars=str_rates[0:5]
star=stars.count('<span class="glyphicon glyphicon-star"></span>')
nums.append(star)
del str_rates[0:5]
for img,title,price,view,num in zip(imgs,titles,prices,views,nums):#釋放抓取的信息,并作結構化處理,存入data字典中。
data={
'title':title.get_text(),
'price':price.get_text(),
'view':view.get_text().split()[0],#view.get_text()的信息包含"views",去掉
'img':img.get('src'),
'num':str(num)+"星"
}
print(data)
結果##

運行結果.png
3. 總結###
-
序列結構的數(shù)據(jù)
與序列有關的內建函數(shù)有:sorted()、reversed()、enumerate()、zip()),其中sorted()和zip()返回一個序列(列表)對象,reversed()、enumerate()返回一個迭代器(類似序列)
與序列有關的操作方法有:max(),min(),len(),+,*,切片,查詢成員資格成員in序列,查詢索引list[2]
for循環(huán)遍歷整個可迭代對象
-
切片
對于序列結構的數(shù)據(jù),切片比如列表list[A:B:C],A表示起始位置,默認是0。B表示結束位置,C表示步長。
AB就是索引,索引和步長都有負值。正序表示時,第B個元素是取不到的。
負步長可以用作倒序取值。相比reverse,它不會改變數(shù)據(jù)結構。

負步長與reverse倒序區(qū)別.png
-
計數(shù)
list.count(元素)