chromedriver 和 firefoxdriver 在 Heroku 上崩溃/停止

问题描述 投票:0回答:1

我正在尝试托管我自己的机器人,它将检查我想购买的平板电脑的价格,并在不和谐的价格变化时发送消息,我正在使用heroku,因为我有来自GitHub学生开发包的免费积分,但是当我运行它时,我得到

selenium.common.exceptions.WebDriverException:消息:进程意外关闭,状态为 255

我在自己的 Firefox 上阅读,但我应该如何在 Heroku 上阅读?使用 chromedriver 给出

2024-10-31T15:09:07.674086 + 00:00 app [worker.1]:selenium.common.exceptions.SessionNotCreatedException:消息:会话未创建:Chrome 无法启动:正常退出。 2024-10-31T15:09:07.674086+00:00 app[worker.1]:(会话未创建:DevToolsActivePort 文件不存在) 2024-10-31T15:09:07.674098+00:00 app[worker.1]: (从 chrome 位置 /app/.cache/selenium/chrome/linux64/130.0.6723.91/chrome 启动的进程不再运行,所以ChromeDriver 假设 Chrome 已崩溃。)

两者都可以在我的电脑上运行 我尝试安装heroku-integrated-firefox-geckodriver buildpack,但它不起作用,因为我需要heroku版本20、18或16,而我有24,我不知道如何降级

带有 ChromeDriver 的 src:

import asyncio
import discord
from discord.ext import commands
import time
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options
from fake_useragent import UserAgent


intents = discord.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(command_prefix='?', description="Checking price lol", intents=intents)

# Initialize global variables
global xkom_price_nokb, xkom_price, xkom_price_lte, lastchecked
xkom_price = None
xkom_price_lte = None
lastchecked = None
xkom_price_nokb = None

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')
    channel = bot.get_channel(1299401756723249246)
    
    # Initial Embed Message
    embed = discord.Embed(title="Lenovo Tab P11 6GB/128GB", color=0x39153e)
    embed.add_field(name="x-kom", value="", inline=False)
    embed.add_field(name="WiFi (no keyboard)", value="Loading...", inline=True)
    embed.add_field(name="WiFi", value="Loading...", inline=True)
    embed.add_field(name="WiFi/LTE", value="Loading...", inline=True)
    embed.add_field(name="Last checked", value="Loading...", inline=False)
    
    if channel:
        async for message in channel.history(limit=None):
            await message.delete()
    else:
        await channel.send(f'Error: Channel not found.')

    global embedsent, embedskirtsent
    embedsent = await channel.send(embed=embed)
    
    # Start monitoring prices
    await monitor_prices()

async def fetch_price(url, whatclass):
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument("--incognito")
    options.add_argument("--nogpu")
    options.add_argument("--disable-gpu")
    options.add_argument("--window-size=1280,1280")
    options.add_argument("--no-sandbox")
    options.add_argument("--enable-javascript")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument('--disable-blink-features=AutomationControlled')

    ua = UserAgent()
    userAgent = ua.random

    driver = webdriver.Chrome(options=options)
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": userAgent})
    
    driver.get(url)

    # output the full-page HTML
    source = driver.page_source

    # release the resources allocated by Selenium and shut down the browser
    driver.quit()

    # Parse the HTML
    soup = BeautifulSoup(source, 'html.parser')
    price_span = soup.find('span', class_=whatclass)
    price = price_span.get_text(strip=True) if price_span else None
    print(price)
    return price


async def monitor_prices():
    global xkom_price, xkom_price_nokb, xkom_price_lte, lastchecked  # Declare them as global
    while True:
        # Fetch prices for the two URLs
        xkom_new_price_nokb = await fetch_price("https://www.x-kom.pl/p/1126296-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-wifi-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)
        xkom_new_price_lte = await fetch_price("https://www.x-kom.pl/p/1145247-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-lte-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)
        xkom_new_price = await fetch_price("https://www.x-kom.pl/p/1152486-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-wifi-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)

        # Get the current time as the last checked time
        lastchecked = time.strftime('%Y-%m-%d %H:%M:%S')

        # Check if prices have changed
        channel2 = bot.get_channel(1299401805683494942)

        if xkom_new_price_nokb and xkom_new_price_nokb != xkom_price_nokb:
            await channel2.send(f"WiFi (no keyboard) price on x-kom changed from {xkom_price_nokb} to {xkom_new_price_nokb}")
            xkom_price_nokb = xkom_new_price_nokb

        if xkom_new_price and xkom_new_price != xkom_price:
            await channel2.send(f"WiFi price on x-kom changed from {xkom_price} to {xkom_new_price}")
            xkom_price = xkom_new_price
        if xkom_new_price_lte and xkom_new_price_lte != xkom_price_lte:
            await channel2.send(f"WiFi/LTE price on x-kom changed from {xkom_price_lte} to {xkom_new_price_lte}")
            xkom_price_lte = xkom_new_price_lte

        # Update the embed message
        embed = discord.Embed(title="Lenovo Tab P11 6GB/128GB", color=0x39153e)
        embed.add_field(name="x-kom", value="", inline=False)
        embed.add_field(name="WiFi (no keyboard)", value=xkom_new_price_nokb or "Not available", inline=True)
        embed.add_field(name="WiFi", value=xkom_price or "Not available", inline=True)
        embed.add_field(name="WiFi/LTE", value=xkom_price_lte or "Not available", inline=True)
        embed.add_field(name="Last checked", value=lastchecked, inline=False)
        await embedsent.edit(embed=embed)

        # Wait for 5 minutes
        await asyncio.sleep(300)


# Run the bot
bot.run('token')

带有 FirefoxDriver 的 src:

import asyncio
import discord
from discord.ext import commands
import time
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

intents = discord.Intents.default()
async def fetch_price(url, whatclass):
    options = Options()
    options.add_argument("-headless")
    options.set_preference("javascript.enabled", True)

    driver = webdriver.Firefox(options=options)
    driver.get(url)

    # output the full-page HTML
    source = driver.page_source

    # release the resources allocated by Selenium and shut down the browser
    driver.quit()

    # Parse the HTML
    soup = BeautifulSoup(source, 'html.parser')
    price_span = soup.find('span', class_=whatclass)
    price = price_span.get_text(strip=True) if price_span else None
    print(price)
    return price


async def monitor_prices():
    global xkom_price, xkom_price_nokb, xkom_price_lte, lastchecked  # Declare them as global
    while True:
        # Fetch prices for the two URLs
        xkom_new_price_nokb = await fetch_price("https://www.x-kom.pl/p/1126296-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-wifi-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)
        xkom_new_price_lte = await fetch_price("https://www.x-kom.pl/p/1145247-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-lte-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)
        xkom_new_price = await fetch_price("https://www.x-kom.pl/p/1152486-tablety-11-lenovo-tab-p11-6gb-128gb-android-12l-wifi-gen-2.html", 'sc-jnqLxu cjLwnY parts__Price-sc-53da58c9-2 hbVORa')
        await asyncio.sleep(3)

        # Get the current time as the last checked time
        lastchecked = time.strftime('%Y-%m-%d %H:%M:%S')

        # Check if prices have changed
        channel2 = bot.get_channel(1299401805683494942)

        if xkom_new_price_nokb and xkom_new_price_nokb != xkom_price_nokb:
            await channel2.send(f"WiFi (no keyboard) price on x-kom changed from {xkom_price_nokb} to {xkom_new_price_nokb}")
            xkom_price_nokb = xkom_new_price_nokb

        if xkom_new_price and xkom_new_price != xkom_price:
            await channel2.send(f"WiFi price on x-kom changed from {xkom_price} to {xkom_new_price}")
            xkom_price = xkom_new_price
        if xkom_new_price_lte and xkom_new_price_lte != xkom_price_lte:
            await channel2.send(f"WiFi/LTE price on x-kom changed from {xkom_price_lte} to {xkom_new_price_lte}")
            xkom_price_lte = xkom_new_price_lte

        # Update the embed message
        embed = discord.Embed(title="Lenovo Tab P11 6GB/128GB", color=0x39153e)
        embed.add_field(name="x-kom", value="", inline=False)
        embed.add_field(name="WiFi (no keyboard)", value=xkom_new_price_nokb or "Not available", inline=True)
        embed.add_field(name="WiFi", value=xkom_price or "Not available", inline=True)
        embed.add_field(name="WiFi/LTE", value=xkom_price_lte or "Not available", inline=True)
        embed.add_field(name="Last checked", value=lastchecked, inline=False)
        await embedsent.edit(embed=embed)

        # Wait for 5 minutes
        await asyncio.sleep(300)


# Run the bot
bot.run('token')

将 webdriver 从 firefox 更改为 chrome,错误已更改但仍然不起作用,我尝试手动下载 firefox 二进制文件并使用存储库部署它,但它不起作用,我尝试安装 heroku-integrated-firefox-geckodriver buildpack 但它不起作用我需要 heroku 版本 20、18 或 16,我有 24,但我不知道如何降级

python selenium-webdriver heroku selenium-chromedriver
1个回答
0
投票

您可以尝试将以下选项参数添加到 chrome 选项并检查

options.add_argument("--disable-dev-shm-usage")
© www.soinside.com 2019 - 2024. All rights reserved.