【问题标题】:No connection could be made because the target machine actively refused it Python无法建立连接,因为目标机器主动拒绝它 Python
【发布时间】:2021-08-25 11:15:22
【问题描述】:

所以我被困在这里无法前进大约 2 周。我正在尝试找到一个元素并对其进行截图,但我不断收到此内容

No connection could be made because the target machine actively refused it

这是我想要获取的元素:

<img id="action_captcha" src="URL HERE" alt="CAPTCHA code" style="vertical-align:middle;">

这是我的代码:

try:
    print("1")
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "action_captcha"))
    )
    print("2")
    image = element.screenshot("Captcha.png")
    print("3")
except Exception as e:
    print(e)

我得到的只是

1
No connection could be made because the target machine actively refused it

我知道没有防火墙阻止连接,因为在此之前我在同一个浏览器实例中有很多元素。我不知道是什么问题。任何帮助表示赞赏。谢谢。

【问题讨论】:

  • 您是否使用任何VPN,请停用并重新运行。
  • @JaydeepDevda 不,我不使用任何 VPN。而且它比“再次运行”要复杂一些,因为我每 2 天只有 3-5 分钟来测试我的代码,所以这就是我花了 2 周时间的原因。

标签: python selenium


【解决方案1】:

“主动拒绝”表示当您尝试连接时主机发送了重置而不是确认。因此,这在您的代码中不是问题。防火墙阻止了连接,或者托管服务的进程没有在该端口上侦听,这可能是因为它根本没有运行,或者因为它正在侦听不同的端口。

您可以在包含浏览器元素的页面中导航吗? 我使用相同的代码没有问题,并且成功地从工作站点截取了验证码。

在另一个页面中尝试一个示例,以确保您尝试访问的页面阻止了所有内容。

例如:

driver.get("https://captchas.net/")
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "captcha_pic"))
)
image = element.screenshot("Captcha.png")

【讨论】:

  • 是的,您的代码确实有效。但令我困惑的是,如果我使用 chrome 和端口 9222 打开网站,并使用chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") 连接到它,我可以毫无问题地找到并截取元素的屏幕截图,即使它是相同的确切代码。我不知道为什么。
【解决方案2】:

我不想承认我在这个问题上被困了 2 周,在发布问题 3 小时后,我解决了它。

我收到此错误的原因是因为我在函数内部初始化了驱动程序,所以我必须将它作为参数传递。这就是我的意思:

def f():
    try:
        #Initaiates the chrome browser
        driver = webdriver.Chrome(path, options=options)
        driver.get(URL)
        x()

    #Catches any errors that might occur
    except Exception as e:
        print(e)
        print("Error")
        driver.quit()

def x():
    try:
        element = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.ID, "action_captcha"))
        )
        
        image = element.screenshot("C:\\Users\\moham\\Desktop\\TLS\\Webscraping\\TLS Appointment\\Captchas\\Original Captcha.png")
    except Exception as e:
        print(e)

所以在这里我必须像这样初始化 X

def x(browser):
    ......

然后这样称呼它

x(driver)

我的 NGL 有点愚蠢。

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 2011-08-24
    • 2023-03-25
    • 2017-05-13
    • 2015-04-05
    • 2016-12-08
    • 2014-09-05
    相关资源
    最近更新 更多