一、網頁HTML結構
在網上爬取了一個網頁,如何在網頁中找到自己想要的內容?
比如,想找到圖片鏈接。網頁中圖片列表的結構如下:
<div class="c s_li zxgx_list l">
<ul>
<li>
<a target="_blank"
href="https://www.xxx.com/HTM/2020/0301/1.html" title="測試">
<img src="https://img.xxx.com/2.jpg"
alt="Python 練習" width="120" height="160" />
<strong>圖片名字</strong>
</a>
</li>
<li>
<a target="_blank"
href="https://www.xxx.com/HTM/2020/0301/2.html" title="測試">
<img src="https://img.xxx.com/2.jpg"
alt="Python 練習" width="120" height="160" />
<strong>圖片名字</strong>
</a>
</li>
<li>
<a target="_blank"
href="https://www.xxx.com/HTM/2020/0301/3.html" title="測試">
<img src="https://img.xxx.com/3.jpg"
alt="Python 練習" width="120" height="160" />
<strong>圖片名字</strong>
</a>
</li>
</ul>
</div>
通過爬蟲,可以得到 HTML 的文本(其他代碼略)。
req = requests.get( url=weburl,params=None,headers=headers )
req.encoding = "gb2312"
req_html = req.text # HTML 的文本
二、分析HTML結構
通過對 HTML 的分析,可以看出圖片都是放在指定的 li 裏的。
<li>
<a target="_blank"
href="https://www.xxx.com/HTM/2020/0301/3.html" title="測試">
<img src="https://img.xxx.com/3.jpg"
alt="Python 練習" width="120" height="160" />
<strong>圖片名字</strong>
</a>
</li>
三、應用正則表達式
在 Python 裏要找出它們,構造正則表達式:
ex = '<li>.*?<img src="(.*?)".*?</li>'
利用正則的 findall( ) 方法找出所有的圖片地址。
L = re.findall(ex, req_html, re.DOTALL|re.I)
這裏,因爲字符串的內容有換行,所以 使用了修飾符 re.DOTALL 。表示讓正則中的 點(.)能代表換行符在內的所有單個字符。
默認情況下, 點(.) 是匹配任意字符,除了換行符。
循環輸出列表 L 的元素示例如下:
https://img.xxx.com/1.jpg
https://img.xxx.com/2.jpg
https://img.xxx.com/3.jpg
會得到所需要的圖片路徑。
四、正則表達式解析
在 Python 開發爬蟲過程中經常會遇到正則表達式,其中 (.*?) 的使用概率較高,那麼這個正則表達式到底什麼意思呢?
-
.*? 表示非貪心算法,表示要精確的配對。
-
.* 表示貪心算法,表示要儘可能多的匹配。
-
( ) 表示要獲取括弧之間的信息。
舉例說明:
req_html = """
你好,我是那天你看到的那個 Red Man。
This is the best day! I have a dream.
Now that the Greeks held Troy and King Priam lay dead,
Aeneas said to his father,
"""
-
正則1:
ex = "t.*\s"
L = re.findall(ex, req_html, re.DOTALL|re.I) # 允許換行,忽略大小寫
print( len(L) )
for item in L:
print( item +"\n")
輸出結果:L 就一個元素,且從“This...” 一直到結尾。
1
This is the best day! I have a dream.
Now that the Greeks held Troy and King Priam lay dead,
Aeneas said to his father,
解析:.* 表示貪心算法,表示要儘可能多的匹配。所以,正則要求從“T” 開頭,直到空格結束,就直接匹配到結尾了。
-
正則2:
ex = "t.*?\s"
輸出結果:
8
This
the
t # best 中的 t
that
the
Troy
to
ther,
解析:.*? 表示非貪心算法,表示要精確的配對。所以,正則表達式要求從“T” 開頭,直到空格結束,儘可能精準較少的去匹配字符串,就找到了8個。會把正則裏的要求的字符,包含 t 和後面的空格(\s)都找出來。
-
正則3:
ex = "t(.*?)\s"
輸出結果:
8
his
he
hat
he
roy
o
her,
解析:( ) 表示要獲取括弧之間的信息。所以,就獲取了 t 和空格(\s)之間的內容。