繁体   English   中英

硒(参数 --headless)+(牵线木偶 = False)

[英]Selenium (argument --headless) + (marionette = False)

我正在尝试使用 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.capabilities 和 firefox_options 这两个不兼容吗? 2.如果我需要将“marionette”设置为False,有没有办法在不打开浏览器的情况下执行这个功能? 或者这个问题还有其他的吗?

希望有人能回答这个问题。

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

我不能谈论功能和 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 的官方导入声明(根据官方文档)是from bs4 import BeautifulSoup

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM