Skip to main content
 首页 » 编程设计

python之Selenium(参数 --headless)+(木偶 = False)

2024年12月31日8www_RR

我正在尝试使用 python 使用 javascript 废弃页面。我是这方面的初学者,所以我阅读了很多教程。我终于发现我需要 selenium、beautiful_soup 和 firefox webdriver。所以我完成了一个功能(我也在添加相关模块)。

import bs4 
import requests 
from urllib.request import Request 
from urllib.request import urlopen as uReq 
from bs4 import BeautifulSoup as soup 
 
from selenium import webdriver 
from selenium.webdriver.firefox.options import Options 
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 
 
def page_souping_js(url): 
    options = Options() 
    options.add_argument("--headless") 
    driver = webdriver.Firefox(firefox_options=options) 
    driver.get(url) 
    complete_page = driver.page_source 
    driver.close() 
    page_soup = soup(complete_page,"html.parser") 
    return page_soup 

这似乎工作正常,直到我尝试用它制作一个 .exe 文件(使用 pyinstaller)并在另一台计算机上运行它(它在我的计算机上工作正常)但我遇到了这个错误:

selenium.common.exceptions.SessionNotCreatedException : Message: Unable to find a matching set of capabilities

所以我再次阅读了这个主题并“修复”了我的代码:

def page_souping_js(url): 
    cap = DesiredCapabilities().FIREFOX 
    cap["marionette"] = False 
    options = Options() 
    options.add_argument("--headless") 
    driver = webdriver.Firefox(capabilities=cap, firefox_options=options) 
    driver.get(url) 
    complete_page = driver.page_source 
    driver.close() 
    page_soup = soup(complete_page,"html.parser") 
    return page_soup 

不过,由于我进行了更改,即使我添加了参数“--headless”,浏览器也会打开。 1. capabilities 和 firefox_options 这两个不兼容吗? 2. 如果我需要将“marionette”设置为 False,有没有办法在不打开浏览器的情况下执行此功能?或者还有其他解决这个问题的方法吗?

希望有人对此有答案。

请您参考如下方法:

好吧,这个问题显然是由于用户在他的机器上安装了一个非常过时的 firefox 版本。不必将功能设置为非默认值,但应更新浏览器。