Python爬蟲實戰(二)

2021-07-26 21:46:21 字數 3025 閱讀 7243

實驗介紹:

本實驗通過使用beautifulsoup方法對網頁進行簡單的爬取工作,並對beatifulsoup方法進行簡單的介紹。 —— 【beautifulsoup開發手冊】

示例網頁如下:

實驗內容:

從本地網頁爬取商品資訊,商品名,**,評分等級等相關資訊

實驗**:

from bs4 import beautifulsoup

path = './index.html'

with open(path, 'r') as f:

soup = beautifulsoup(f.read(), 'lxml')

titles = soup.select("body > div > div > div.col-md-9 > div > div > div > div.caption > h4 > a")

images = soup.select("body > div > div > div.col-md-9 > div > div > div > img")

reviews = soup.select("body > div > div > div.col-md-9 > div > div > div > div.ratings > p.pull-right")

prices = soup.select("body > div > div > div.col-md-9 > div > div > div > div.caption > h4.pull-right")

stars = soup.select("div > div.ratings > p:nth-of-type(2)")

print(len(titles), len(images), len(reviews), len(prices), len(stars))

for title, image, review, price, star in zip(titles, images, reviews, prices, stars):

title_content = title.get_text()

review_content = review.get_text()

price_content = price.get_text()

image_content = image.get("src")

stars_count = len(star.find_all("span", "glyphicon glyphicon-star"))

data =

print(data)

實驗總結使用beautifulsoup爬取網頁內容的主要步驟python中的zip函式簡介:

zip函式接受任意多個(包括0個和1個)序列作為引數,返回乙個tuple列表。具體意思不好用文本來表述,直接看示例:

1.示例1:

複製**

x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

print xyz

複製**

執行的結果是:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

從這個結果可以看出zip函式的基本運作方式。

2.示例2:

x = [1, 2, 3]

y = [4, 5, 6, 7]

xy = zip(x, y)

print xy

執行的結果是:

[(1, 4), (2, 5), (3, 6)]

從這個結果可以看出zip函式的長度處理方式。

3.示例3:

x = [1, 2, 3]

x = zip(x)

print x

執行的結果是:

[(1,), (2,), (3,)]

從這個結果可以看出zip函式在只有乙個引數時運作的方式。

4.示例4:

x = zip()

print x

執行的結果是:

從這個結果可以看出zip函式在沒有引數時運作的方式。

5.示例5:

複製**

x = [1, 2, 3]

y = [4, 5, 6]

z = [7, 8, 9]

xyz = zip(x, y, z)

u = zip(*xyz)

print u

複製**

執行的結果是:

[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

一般認為這是乙個unzip的過程,它的執行機制是這樣的:

在執行zip(*xyz)之前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

那麼,zip(*xyz) 等價於 zip((1, 4, 7), (2, 5, 8), (3, 6, 9))

所以,執行結果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)]

注:在函式呼叫中使用*list/tuple的方式表示將list/tuple分開,作為位置引數傳遞給對應函式(前提是對應函式支援不定個數的位置引數)

6.示例6:

x = [1, 2, 3]

r = zip(* [x] * 3)

print r

執行的結果是:

[(1, 1, 1), (2, 2, 2), (3, 3, 3)]

它的執行機制是這樣的:

[x]生成乙個列表的列表,它只有乙個元素x

[x] * 3生成乙個列表的列表,它有3個元素,[x, x, x]

zip(* [x] * 3)的意思就明確了,zip(x, x, x)

python爬蟲實戰

python python基礎 python快速教程 python學習路線圖 python大資料學習之路 python爬蟲實戰 python pandas技巧系 量化小講堂 python機器學習入門資料梳理 學習群 大資料 python資料探勘2 323876621 r r語言知識體系 怎樣學習r ...

Python網路爬蟲實戰 二 資料解析

根據爬取下來的資料,我們需要寫不同的解析方式,最常見的一般都是html資料,也就是網頁的原始碼,還有一些可能是json資料,json資料是一種輕量級的資料交換格式,相對來說容易解析,它的格式如下。但是對於爬取下來是乙個html資料,其中標籤結構可能十分複雜,而且不同html的結構可能存在差異,所以解...

Python爬蟲實戰2 0

這次實戰的內容是非同步載入 非同步載入和普通的數字下表迭代的url不同的地方在於不能直接通過乙個for迴圈來獲取每乙個頁面的內容。如何判別翻頁是否是非同步載入的呢?開啟瀏覽器檢查,然後定位到頁面內容的那部分html 然後在瀏覽器按下翻頁按鈕,如果發現html 部分內容閃了一下,那麼說明網頁是通過非同...