Embedding Python in C++
-
I have tried using Selenium with both the PythonQt and the Python.h libraries. I have a Ubuntu 16.04 platform using QT Creator 4.2.2 with Qt5.8.0. I can get everything setup with either interpreter and call a simple Python class for strings from Qt. However when I try and use Selenium I end up having problems (running py script for Selenium from the prompt works fine). For instance, using python.h When PyObject_GetAttrString(pModule, "browser") is called I get a segmentation fault. I am assuming that I need to load the selenium module or set the python path to it in Qt, but I am not clear on how to do this with multiple modules/paths. This is my python code browser.py:
from selenium import webdriver
from selenium.webdriver.common.keys import Keysclass browser():
def __init__(self):
self.driver = None
self.webelement = None
def getbrowser(self, name):
if name == "chrome":
self.driver = webdriver.Chrome()
elif name == "firefox":
self.driver = webdriver.Firefox()
def getpage(self,page):
self.driver.get(page)
def getsearchelement(self,elementname):
self.webelement = self.driver.find_element_by_name(elementname)
def getsearch(self,search):
self.webelement.send_keys(search + Keys.RETURN)
def stopbrowser(self):
self.driver.quit()""" Following runs fine from prompt, crashes in PythonQt/python.h
browser = webdriver.Firefox()
browser.get('https:\\search.yahoo.com')
elem = browser.find_element_by_name('p') # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)
browser.quit()
"""Here is the routine from my c++ code
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this); // Doing it here for debugging PyObject \*pName, \*pModule, \*pFuncSet, \*pValue, \*pClass, \*pInst, \*pArgs; PyObject \*pGetBrowser, \*pGetPage, \*pGetSearchElement, \*pGetSearch, \*pStopBrowser; // Initialize the Python Interpreter Py\_Initialize(); PySys\_SetPath("/home/user/CppCode/StocksWeb/src/"); // Build the name object pName = PyString\_FromString("browser"); // Load the module object pModule = PyImport\_ImportModule("browser"); pClass = PyObject\_GetAttrString(pModule, "browser"); if(pClass != NULL && pModule != NULL ) { pArgs = Py\_BuildValue("( )"); pInst = PyEval\_CallObject(pClass, pArgs); if ( pInst != NULL ) { pGetBrowser = PyObject\_GetAttrString(pInst, "getbrowser"