PYTHON爬蟲將相對路徑轉化為絕對路徑

在寫爬蟲的時候經常會遇到相對路徑,比如下面這種:

<a href="01/110107.html">石景山區</a>

我們當然可以直接用字元串拼接基地址和相對地址,但是,相對路徑的寫法除了上面這種還有其他的,比如:

<a href="/01/110107.html">石景山區</a><a href="./01/110107.html">石景山區</a><a href="../01/110107.html">石景山區</a>

還要分別寫拼接的代碼,有沒有優雅的辦法呢?顯然python不會讓我們失望的。

python2 的urlparse 模塊裡面的 urljoin 函數可以完美解決這個問題。

>>> from urlparse import urljoin >>> urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html") http://www.asite.com/folder/anotherpage.html >>> urljoin("http://www.asite.com/folder/currentpage.html", "folder2/anotherpage.html") http://www.asite.com/folder/folder2/anotherpage.html >>> urljoin("http://www.asite.com/folder/currentpage.html", "/folder3/anotherpage.html") http://www.asite.com/folder3/anotherpage.html >>> urljoin("http://www.asite.com/folder/currentpage.html", "../finalpage.html") http://www.asite.com/finalpage.html

而python3,urljoin被整合到urllib.parse,引用變成:

>>> from urllib.parse import urljoin

推薦閱讀:

初識Scrapy,在充滿爬蟲的世界裡做一個好公民
使用requests+beautifulsoup爬取你想要的數據
愛奇藝人物信息scrapy-redis
python中 if-else 與 try-except的轉換 與while 與 whileTrue-try-except的轉換
輪帶逛終極版! 抓取輪子哥(vczh)全部知乎動態

TAG:Python | python爬蟲 |