无法使用 strip 或 replace 删除前导 \n

Can't remove leading \n using strip or replace

我正在尝试从以下文本中获取 IP:Port:

{
  "supportsHttps": true,
  "protocol": "http",
  "ip": "149.28.159.132",
  "port": "8080",
  "get": true,
  "post": true,
  "cookies": true,
  "referer": true,
  "user-agent": true,
  "anonymityLevel": 1,
  "websites": {
    "example": true,
    "google": true,
    "amazon": false,
    "yelp": false,
    "google_maps": false
  },
  "country": "US",
  "unixTimestampMs": 1558097368515,
  "tsChecked": 1558097368,
  "unixTimestamp": 1558097368,
  "curl": "http://149.28.159.132:8080",
  "ipPort": "149.28.159.132:8080",
  "type": "http",
  "speed": 89.52,
  "otherProtocols": {},
  "verifiedSecondsAgo": 1249
}

我正在使用此代码:

def gimmeproxy():
    r=requests.get("https://gimmeproxy.com/api/getProxy?api_key=45785302-3264-4694-99e1-7c6628c90e6c&get=true&country=US&protocol=http&supportsHttps=true&user-agent=true&websites=google&anonymityLevel=1")
    contents=str(r.content)
    content=contents.split(',')
    IP=content[20]
    print(IP)

    #IP=IP.replace(':','')
    IP = IP.replace('"', '')
    IP = IP.replace(',', '')
    IP = IP.replace("\n", "")
    IP = IP.replace('ipPort', '')
    IP = IP.replace(' ', '')
    IP = IP.lstrip()

    print(IP)
    return IP

但是,无论我做什么,输出总是显示\n

C:\Users\brian>python freelancer_scripts_gimmeproxy.py
\n  "ipPort": "104.248.85.190:8080"
\n:104.248.85.190:8080

我试过剥离和替换我能想到的一切,但就是无法摆脱这个\n。我怎样才能从文本中得到 IP:Port 地址?

你得到的就是JSON。将其转换为字典以获得所需的值会更容易(您已经在使用 requests 因此我们可以使用 json 方法):

def gimmeproxy():
    r = requests.get("https://gimmeproxy.com/api/getProxy?api_key=45785302-3264-4694-99e1-7c6628c90e6c&get=true&country=US&protocol=http&supportsHttps=true&user-agent=true&websites=google&anonymityLevel=1")
    contents = r.json()  # transform into a dictionary
    ip = contents["ip"]
    port = contents["port"]
    print(ip)
    print(port)
    return ip