【问题标题】:Merge a string to URL in python在python中将字符串合并到URL
【发布时间】:2019-11-27 22:58:37
【问题描述】:

我必须将“字符串”类型的硬编码路径连接到一个 URL 以获得一个 URL 的结果。

url(不以“/”结尾)+“/path/to/file/”=new_url

我尝试使用 URL 连接进行连接,也尝试使用简单字符串 concat,但结果不是可以访问的 URL。 (不是URL地址无效)

mirror_url = "http://amazonlinux.us-east- 
2.amazonaws.com/2/core/latest/x86_64/mirror.list"

response = requests.get(mirror_url)
contents_in_url = response.content


## returns a URL as shown below but of string type which cannot be 
##concatenated to another string type which could be requested as a valid 
##URL.
'http://amazonlinux.us-east- 2.amazonaws.com/2/core/2.0/x86_64/8cf736cd3252ada92b21e91b8c2a324d05b12ad6ca293a14a6ab7a82326aec43'

path_to_add_to_url = "/repodata/primary.sqlite.gz"

final_url = contents_in_url + path_to_add_to_url

期望的结果:

不省略该文件的任何路径。

final_url = "http://amazonlinux.us-west-2.amazonaws.com/2/core/2.0/x86_64/8cf736cd3252ada92b21e91b8c2a324d05b12ad6ca293a14a6ab7a82326aec43/repodata/primary.sqlite.gz"

【问题讨论】:

  • 那么你得到的结果是什么?你看过stackoverflow.com/questions/1793261/…吗?
  • @intotecho 是的,但就我而言,我必须坚持使用“请求”库,不能使用“urllib”。

标签: python-3.x string python-2.7 url python-requests


【解决方案1】:

你需要通过response.text方法获取第一个响应的内容,而不是response.content

import requests

mirror_url = "http://amazonlinux.us-east-2.amazonaws.com/2/core/latest/x86_64/mirror.list"

response = requests.get(mirror_url)
contents_in_url = response.text.strip()

path_to_add_to_url = "/repodata/primary.sqlite.gz"

response = requests.get(contents_in_url + path_to_add_to_url)

with open('primary.sqlite.gz', 'wb') as f_out:
    f_out.write(response.content)

print('Downloading done.')

【讨论】:

  • 请求时问题中的 'mirror_url' 给出了一个字符串,当与 '/repodata/primary.sqlite.gz' 连接时返回一个字符串,无法请求该字符串以获取响应 200。
  • Kesely 谢谢,但不幸的是,这在我的情况下似乎不起作用,因为“mirror_url”的内容中似乎也有一个 URL。奇怪的是它不起作用。
  • 下面的代码似乎不起作用。 ` 导入请求 url = "amazonlinux.us-east- 2.amazonaws.com/2/core/latest/x86_64/mirror.list" response = requests.get(url) text = response.content repo_path = "/repodata/primary.sqlite. gz" res = requests.get(text + repo_path) 打印 res `
  • @prash 更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2021-07-08
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
相关资源
最近更新 更多