Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

urlparseしたurlにqueryを追加して元のurlにもどす

More than 3 years have passed since last update.
概要

こんな感じのURLがあるとして、https://api.twitter.com/1.1/statuses/user_timeline.json&screen_name=drwtsn64
urllib.parse.urlparse()したあとに
query部分にcount=200を追加して、元のURLに戻す方法。

検証コード
import urllib.parse

url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=drwtsn64'
parsed = urllib.parse.urlparse(url)

print(parsed)

query = urllib.parse.parse_qs(parsed.query, True)

print(query)

query['count'] = 200

print(query)

encoded = urllib.parse.urlencode(query, True)

print(encoded)

reversed = urllib.parse.ParseResult(parsed.scheme, parsed.netloc, parsed.path, parsed.params, encoded, parsed.fragment).geturl()

print(reversed)
出力
ParseResult(scheme='https', netloc='api.twitter.com', path='/1.1/statuses/user_timeline.json', params='', query='screen_name=drwtsn64', fragment='')
{'screen_name': ['drwtsn64']}
{'screen_name': ['drwtsn64'], 'count': 200}
screen_name=drwtsn64&count=200
https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=drwtsn64&count=200
注意点

urlencode()に渡してるqueryはdictionaryなので、クエリ文字の順番は保証されない

drwtsn64
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away