Selenium(论点 - 无头)+(marionette = False)

时间:2018-05-28 21:05:34

标签: python selenium pyinstaller

我正在尝试使用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:消息:无法找到一组匹配的功能

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

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.这两个功能和firefox_options是否不兼容? 2.如果我需要将“marionette”设置为False,有没有办法在没有浏览器打开的情况下执行此功能?或者是否存在另一个问题?

希望有人能得到答案。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我不能谈论功能和firefox_options的兼容性,但我已经取得了一些成功:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup

def page_souping_js(url):
    options = Options()
    options.set_headless(True)
    driver = webdriver.Firefox(firefox_options=options)
    driver.get(url)
    complete_page = driver.page_source
    driver.close()
    page_soup = BeautifulSoup(complete_page, "lxml")
    return page_soup

这应该在不打开浏览器的情况下返回源html。通过PyInstaller进行此操作似乎也没有引起任何问题。

旁注,BeautifulSoup的官方导入声明(根据official documentation)是from bs4 import BeautifulSoup

答案 2 :(得分:0)

确保您正在使用此路径访问“ App”文件夹中的firefox.exe文件。 'path \ to \ FirefoxPortable \ App \ Firefox \ firefox.exe'

对于64位版本,请使用以下路径: 'path \ to \ FirefoxPortable \ App \ Firefox64 \ firefox.exe'