簡體   English   中英

無法使用條帶或替換刪除前導\ n

[英]Can't remove leading \n using strip or replace

我試圖從以下文本中獲取IP:端口:

{
  "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:端口地址?

你得到的是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM