網(wǎng)站
Paste_Image.png
代碼
from bs4 import BeautifulSoup
info = []
with open('D:/Plan-for-combating-master/week1/1_2/1_2answer_of_homework/index.html','r') as wb_data:
soup = BeautifulSoup(wb_data, 'lxml')
images = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > img')
titles = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4:nth-of-type(2) > a')
prices = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.caption > h4.pull-right')
stars = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p:nth-of-type(2)')
reviews = soup.select('body > div:nth-of-type(1) > div > div.col-md-9 > div:nth-of-type(2) > div > div > div.ratings > p.pull-right')
for title,image,price,star,review in zip(titles,images,prices,stars,reviews):
data = {
'title':title.get_text(),
'image':image.get('src'),
'price':price.get_text().replace('$',''),
'star':len(star.find_all('span', class_='glyphicon glyphicon-star')),
'review':review.get_text().split()[0]
}
info.append(data)
print(info)
問題
- 從網(wǎng)頁上直接copy selector時(shí),有個(gè)div標(biāo)簽序號(hào)是錯(cuò)的。應(yīng)該是1,copy下來的結(jié)果是2。最開始沒有意識(shí)到,出來的結(jié)果一直有錯(cuò)...后來一步步檢查才發(fā)現(xiàn),不知道為何網(wǎng)頁自動(dòng)copy的也會(huì)出這種錯(cuò)呢?
- 想到一個(gè)問題:如果一個(gè)標(biāo)簽A下,有B/C/D三個(gè)并列的標(biāo)簽,但我只想爬取B/D兩個(gè)標(biāo)簽下的內(nèi)容。如何在select的時(shí)候選中這特定的兩個(gè)標(biāo)簽?zāi)兀恳驗(yàn)橐淳拖拗苨elector末端為A,但這樣就把三個(gè)都抓進(jìn)去了。不知道一個(gè)標(biāo)簽下存在三個(gè)并列的不同標(biāo)簽,是否是一個(gè)合理的html格式。
總結(jié)
- 限制標(biāo)簽順序的時(shí)候可以用A.class_name,也可以用A.nth-of-type(n)。直接從網(wǎng)頁上copy的selector是nth-child(n),可能會(huì)報(bào)錯(cuò),需要注意。
- find_all方法查找特定標(biāo)簽里的內(nèi)容時(shí),可以根據(jù)class名稱查找,此時(shí)class要加一個(gè)下劃線class_
- 總結(jié)起來就是,先用beautifulsoap將網(wǎng)頁的內(nèi)容讀入,再根據(jù)select的參數(shù)將想要的標(biāo)簽內(nèi)容提取出來成為一個(gè)list,最后在這些list里再使用各種方法獲取標(biāo)簽里面的內(nèi)容就可以了。有的是直接get_text獲取標(biāo)簽內(nèi)的文本信息,圖片一般是get('src)等等。當(dāng)然,根據(jù)你拿到的信息,可以再做一些別的字符串處理,最終呈現(xiàn)想要的結(jié)果輸出就可以了。
沈 閱
20160826