LoginSignup
5
2

More than 3 years have passed since last update.

PythonのURL結合にはos.path.joinではなくurlparse.urljoinを使う

Last updated at Posted at 2020-08-02

PythonでcsvファイルからURL一覧を取得して、そのURLを結合させたいときに躓いたのでメモ

うまくいかなかった方(os.path.join)

import os.path

channel_urls = ['/channel/UCVrJcoR8hUN9Rn7uPI4z6NQ']

for i in channel_urls:
    root_url = 'https://www.youtube.com'
    channel_url = ('%s' % i)
    channel_about_url = urlparse.urljoin(youtube_url, channel_url, 'about')
    print(self.open_channel_url)

# /channel/UCVrJcoR8hUN9Rn7uPI4z6NQ/about           // 「https://www.youtube.com」が入らない

うまくいった方(urlparse.urljoin)

まずはモジュールをインストール
(以下のコマンドたちは$ histroyの出力結果から拾ったので、全部必要だとは限りません)

tamenal.
$ pip3 install urllib3
$ pip install git+https://github.com/mitsuhiko/flask-oauth
$ pip install urlparse3

ソース

sample.py
try:
    import urlparse
except ImportError:
    import urllib.parse as urlparse

channel_urls = ['/channel/UCVrJcoR8hUN9Rn7uPI4z6NQ']

for i in channel_urls:
    root_url = 'https://www.youtube.com'
    channel_url = ('%s' % i)
    channel_about_url = urlparse.urljoin(youtube_url, channel_url, 'about')
    print(self.open_channel_url)
# https://www.youtube.com/channel/UCVrJcoR8hUN9Rn7uPI4z6NQ/about

参考
https://qiita.com/Go-zen-chu/items/d7e6b9af0bd90c7aabca
https://www.it-swarm.dev/ja/python/python%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%ABurlparse%E3%82%92%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%E3%83%AB%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%9B%E3%82%93/961197002/
https://github.com/heroku/kafka-helper/issues/6

5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2