【问题标题】:Get request with Python loop使用 Python 循环获取请求
【发布时间】:2020-05-09 18:48:06
【问题描述】:

我一直在做这个简单的项目,通过搜索获取​​请求的来源来判断 Instagram 用户是否已经被占用或仍然可用

无论如何,当我使用手动用户输入实现脚本时,它工作得非常好,代码如下:

    import requests

def insta_check():
    i = 10
    while i > 0:
        print()
        username = input(" Input user to check or Enter (q) 2 quit : ").lower()

        if username == 'q':
            print()
            print(" Good Bye ^_^ ")
            break
        print()
        url = 'https://www.instagram.com/' + username

        x = requests.get(url)
        y = x.text

        if 'Page Not Found' in y:
            print("[+] The user [ {} ] is Available or bieng disabled by the user owner :) ".format(username))
        elif 'Page Not Found' not in y:
            print("[+] The user [ {} ] is Not Available :( ".format(username))
        print()
insta_check()

但是当我尝试从输出文件中获取输入时,get 请求开始给我错误的结果(它表明所有用户都可用) IDK 为什么,这就是我要问的问题

    import requests

f = open("users", "r")

def insta_checker():


    for username in f:


        url = 'https://www.instagram.com/' + username
        x = requests.get(url)
        y = x.text

        if 'Page Not Found' in y:
            print("[+] The user [ {} ] is Available :) ".format(username))
        elif 'Page Not Found' not in y:
            print("[+] The user [ {} ] is Not Available :( ".format(username))
        print()


insta_checker()

【问题讨论】:

  • 您确定您的脚本不只是因为 instagram 不想被抓取而被阻止吗?
  • 我跑了同样的事情,它对我有用。也许 instagram 屏蔽了你?尝试打印 get 请求的输出。
  • 您在任何时候都没有从文件中读取()
  • 我不认为我被阻止了,因为它有效但结果错误,为了阅读,我从文件中读取了所有用户,如果你想检查 print(url) 和你会看到它正在正常获取输入

标签: python get request


【解决方案1】:

当您执行 for username in f 时,它会读取整行,包括末尾的 \n 字符并将其附加到 url,这就是它显示用户名可用的原因。您需要 strip() 用户名删除任何空格(或 rstrip() 仅从右侧删除)。

另外,完成后最好使用with open('file', 'r') as f:自动关闭文件,例如:

import requests

def insta_checker():
    with open('users', 'r') as f:
        for username in f:
            username = username.rstrip() # remove newline character
            url = 'https://www.instagram.com/' + username
            x = requests.get(url)
            y = x.text
            if 'Page Not Found' in y:
                print("[+] The user [ {} ] is Available :) ".format(username))
            elif 'Page Not Found' not in y:
                print("[+] The user [ {} ] is Not Available :( ".format(username))
            print()

insta_checker()

或者,您可以使用f.read().splitlines() 仅删除每行的尾随换行符:

with open('users', 'r') as f:
    for username in f.read().splitlines():
        # rest of code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 2015-03-04
    相关资源
    最近更新 更多