1. 程式人生 > >Python 爬蟲技巧1 | 將爬取網頁中的相對路徑轉換為絕對路徑

Python 爬蟲技巧1 | 將爬取網頁中的相對路徑轉換為絕對路徑

1.背景:

在爬取網頁中的過程中,我對目前爬蟲專案後端指令碼中拼接得到絕對路徑的方法很不滿意,今天很無意瞭解到在python3 的 urllib.parse模組對這個問題有著非常完善的解決策略,真的是上天有眼,感動!

2.urllib.parse模組

This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

根據Python官網文件,我們可以大致瞭解到這個模組的3個主要功能,一是將URL分解為各個部分,二是將URL各個部分拼接成URL,三是將一個相對路徑轉換成絕對路徑。

我們主要用它的第三個功能,使用的函式是

urllib.parse.urljoin(base, url, allow_fragments=True)

3.程式碼實現例子:

程式碼:

from urllib import parse

page_url = 'http://fcg.gxepb.gov.cn/ztzl/hjwfbgt/'
new_url = '../../hjzf/xzcf/201811/t20181102_46347.html'

new_full_url = parse.urljoin(page_url, new_url)
print(new_full_url)

結果為:

http://fcg.gxepb.gov.cn/hjzf/xzcf/201811/t20181102_46347.html

可以說是相當棒了!

4.官方相關文件連結:

urllib.parse — Parse URLs into components