首页 > 解决方案 > 我如何阅读里面的文字

在蟒蛇?

问题描述

我正在尝试制作一个脚本来检测是否使用了 Instagram 用户名。我发现使用 url https://www.instagram.com/{username}/?__a=1将填写有关帐户的信息,如果名称存在,但如果名称不存在,页面将只有{} 在 pre 中,仅此而已。

我正在使用 Requests 和 BeautifulSoup 来抓取页面。这是我编写的用于测试的脚本:

import requests
from bs4 import BeautifulSoup

username = input("Enter the username you would like to check:")
account_url=('https://www.instagram.com/' + username + '/?__a=1')
r = requests.get(account_url)

print(r.text)

显示文本有效,但即使我输入了不存在的用户名或随机乱七八糟的字母,它总是返回一堆我在实际 url 上的检查元素中看不到的 html。如何让它只返回 pre 中的文本?我只是想检测该站点是否没有显示任何内容,以便确定它是否是已使用的用户名。

此外,当您使用不存在的用户名加载 instagram ?__a=1 url 时,inspect 元素会说存在错误 404,但在 python 中测试 requests 变量的状态总是返回 200,即成功。我对python非常缺乏经验,因为我已经很长时间没有使用它了,所以非常感谢一些帮助。

标签: pythonhtmlweb-scrapingbeautifulsouppython-requests

解决方案


如果你想要一个没有被占用的账户列表,你可以使用这个

import requests
not_taken = []
user_names = ["randomuser1", "randomuser2", "randomuser3", "etc..."]

for name in user_names:
    response = requests.get(f"https://www.instagram.com/{name}/?__a=1")
    if response.status_code == 404:
        not_taken.append(name)

现在您可以根据需要使用 not_taken ,例如:

print(not_taken)

推荐阅读