简体   繁体   English

使用python捕获API自动下载文件

[英]Capturing API automatic download file with python

I am trying to use the api at this url https://freeapi.robtex.com/pdns/reverse/(ip_address_here) I am new to coding so if im just completely using the wrong packages bear with me... When entering the URL with the ip address appended to the end it automatically downloads the json response as a file and displays no webpage. 我正在尝试在此URL上使用api https://freeapi.robtex.com/pdns/reverse/(ip_address_here)我是编码新手,因此,如果我只是完全使用了错误的程序包,请耐心等待... IP地址附加在末尾的URL会自动将json响应下载为文件,并且不会显示任何网页。 I would like to save this downloaded file to a temp directory and keep it for further parsing later on in my tool. 我想将此下载文件保存到一个临时目录中,并保留下来以供以后在我的工具中进行进一步解析。 I have tried using request.get, urlopen, and urllib but I only get the response code (200) not the actual file. 我尝试使用request.get,urlopen和urllib,但我只得到响应代码(200),而不是实际文件。 Or it seems to be working but the website will not connect / respond to my script and it times out. 或它似乎正在运行,但网站无法连接/响应我的脚本,并且超时。 I also added User agent headers copied when I was on their website. 我还添加了我在其网站上复制的用户代理标头。 Main argument is using argparse so this can be used as a command line tool. 主要参数是使用argparse,因此可以用作命令行工具。 The function getData is where im trying to get the file to download. 函数getData是我试图获取文件下载的地方。

def getData(x):
    pdns_url="https://freeapi.robtex.com/pdns/reverse/"+x
    headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
       AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 
       Safari/537.36'}
    #req=urllib.request.Request(pdns_url)
    #resp=urllib.request.urlopen(pdns_url)
    resp= requests.get(pdns_url, headers=headers)
    respData=resp.read()
    return respData

def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url", help="The IP to lookup.", type=str)
    parser.add_argument("-o", "--output", help="Output results to a file.", 
       action="store_true")
    args=parser.parse_args()

    result=getData(args.url)
    if args.output:
        f=open("Dns_Lookup", "a")
        f.write(str(result))
    else:
        print(str(args.url))

    if __name__=='__main__':
        Main()

Try starting with the basics: 尝试从基础开始:

import requests

r = requests.get('https://freeapi.robtex.com/pdns/reverse/')
print(r.content)
open('temp.txt', 'wb').write(r.content)

This works without adding the HTTP header. 这无需添加HTTP标头即可工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM