將爬取網頁中的相對路徑轉換為絕對路徑


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

感謝:轉自將爬取網頁中的相對路徑轉換為絕對路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM