无法使用剥离或替换删除前导\ n

时间:2019-05-17 16:00:54

标签: python replace strip

我正在尝试从以下文本中获取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:端口地址?

1 个答案:

答案 0 :(得分:5)

您得到的称为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