E
======================================================================
ERROR: test_LoginCorrect (__main__.LoginCorrect)
----------------------------------------------------------------------
Traceback (most recent call last):
File "demo.py", line 12, in test_LoginCorrect
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 248, in
start_session
self.session_id = response['sessionId']
TypeError: string indices must be integers
----------------------------------------------------------------------
Ran 1 test in 20.878s
//Formatting is not properly done
FAILED (errors=1)
My test case file :
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class LoginCorrect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Remote(command_executor='http://0.0.0.0:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX)
def test_LoginCorrect(self):
user ="shubh"
pwd= "sha123#56su"
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
driver.get("http://0.0.0.0:8000/login")
elem = driver.find_element_by_id("id_username")
elem.send_keys(user)
elem = driver.find_element_by_id("id_password")
elem.send_keys(pwd)
driver.find_element_by_class_name('btn-block').click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
My machine has Linux 16.04LTS and selenium 3.3.0
Can somebody figure out this problem.
Related
I was trying splinter as an alternative of selenium but it's not working correctly.
Traceback (most recent call last):
File "C:\scrapper.py", line 14, in <module>
browser = Browser('flask', app=app)
File "C:\.env\lib\site-packages\splinter\browser.py", line 121, in Browser
return get_driver(driver, retry_count=retry_count, *args, **kwargs)
File "C:.env\lib\site-packages\splinter\browser.py", line 92, in get_driver
return driver(*args, **kwargs)
TypeError: 'NoneType' object is not callable
my program
from flask import Flask
app = Flask(__name__)
#app.route('/')
def main():
return 'Hello, World!'
#app.route('/<name>')
def hello_world(name):
return 'Hello, {name}!'.format(name=name)
# initiate splinter flask client
from splinter import Browser
browser = Browser('flask', app=app)
print(browser.html)
I'm trying to get a PyQt lineEdit widget to place its' contents within a variable in the module 'followup' but for some reason the module does not recognize the PyQt MainWindow as being properly instantiated.
#workbot_main.py
import gspread
import os
import sys
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\workbot.py"))
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\initial.py"))
sys.path.append(os.path.abspath(r"C:\Users\leamy\Desktop\work bot\followup.py"))
import threading
import followup
import initial
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QApplication
from workbot import *
import workbot
#workbot.py is the QTdesigner file containing the widgets,
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
followup_start_button = self.ui.followup_start_button
followup_start_button.clicked.connect(threads.begin_initialize)
def followup_starting_number(self):
num = self.ui.lineEdit.text()
return num
def begin_initialize(self):
t1 = threading.Thread(target = followup.initialize, args = ())
t1.start()
threads = Threads()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
widget = MainWindow()
widget.show()
app.exec_()
#followup.py
import workbot_main
def initialize():
row_number.number = workbot_main.MainWindow.followup_starting_number()
print(row_number.number)
I get this error
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\leamy\anaconda3\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\leamy\anaconda3\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\leamy\Desktop\work bot\followup.py", line 313, in initialize
row_number.number = workbot_main.MainWindow.followup_starting_number()
TypeError: followup_starting_number() missing 1 required positional argument: 'self'
I can't understand why it doesn't work.
Edit:
If I try to use
row_number.number = workbot_main.widget.followup_starting_number()
instead of
row_number.number = workbot_main.MainWindow.followup_starting_number()
I get this error
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\leamy\anaconda3\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\leamy\anaconda3\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\leamy\Desktop\work bot\followup.py", line 314, in initialize
row_number.number = workbot_main.widget.followup_starting_number()
AttributeError: module 'workbot_main' has no attribute 'widget'
I don't know if that is related.
I am using python 3.5 (32bit), win10-64bit, OpenOPC, and I have downloaded pywin32 build 64bit. I have run the following python code:
import OpenOPC
import time
opc=OpenOPC.client()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int4','Random.Real4']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(5)
but I always get this error message:
Traceback (most recent call last): File "C:\Program Files
(x86)\Python35-32\lib\multiprocessing\queues.py", line 241, in _feed
obj = ForkingPickler.dumps(obj) File "C:\Program Files (x86)\Python35-32\lib\multiprocessing\reduction.py", line 50, in dumps
cls(buf, protocol).dump(obj)
_pickle.PicklingError: Can't pickle : attribute lookup datetime on pywintypes failed.
I have found a solution:
import OpenOPC
import time
import pywintypes
pywintypes.datetime = pywintypes.TimeType
opc=OpenOPC.client()
opc.servers()
opc.connect('Matrikon.OPC.Simulation.1')
tags =['Random.Int1','Random.Real4','Random.Int2','Random.Real8']
while True:
try:
value = opc.read(tags,group='Group0',update=1)
print (value)
except OpenOPC.TimeoutError:
print ("TimeoutError occured")
time.sleep(1)
I know this topic has been came up many times, but I am totally stuck and need help. Please tell me what I have done wrong here and how to fix it. Thanks in advance.
# testcase1.py
import unittest
import sys
class Global:
b = 0
class Util_Case_ID(unittest.TestCase):
def setUp(self):
sys.path.insert(0, 'C:/**/views')
sys.path.insert(0, 'C:/**/app')
sys.path.insert(0, 'C:/**/tests')
from app.views.utility import method_a
Global.b = len(method_a())
def test1(self):
self.assertEqual(Global.b, 11)
def tearDown(self):
sys.path.remove('C:/***/app/views')
sys.path.remove('C:/***/app')
sys.path.remove('C:/*/tests')
if __name__ == "__main__":
unittest.main()
AttributeError: module 'UnitTests' has no attribute 'testcase1'
The Traceback is as follows:
Traceback (most recent call last):
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\utrunner.py", line 167, in <module>
all.addTests(testLoader.loadTestsFromTestClass(getattr(module, a[1])),
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\loader.py", line 108, in loadTestsFromTestClass
return self.suiteClass(ContextList(cases, context=cls))
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 253, in __call__
return self.makeSuite(tests, context, **kw)
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 291, in makeSuite
for ancestor in self.ancestry(context):
File "C:\Users\******\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\suite.py", line 269, in ancestry
yield resolve_name('.'.join(ancestors))
File "C:\Users\*****\AppData\Roaming\JetBrains\PyCharm Edu 3.5.1\helpers\pycharm\nose_helper\util.py", line 70, in resolve_name
obj = getattr(obj, part)
AttributeError: module 'UnitTests' has no attribute 'testcase1'
Process finished with exit code 1
I have a piece of code to test scrapy. My goal is to use scrapy without having to call the scrapy command from the terminal, so I can embed this code somewhere else.
The code is the following:
from scrapy import Spider
from scrapy.selector import Selector
from scrapy.item import Item, Field
from scrapy.crawler import CrawlerProcess
import json
class JsonWriterPipeline(object):
file = None
def open_spider(self, spider):
self.file = open('items.json', 'wb')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
class StackItem(Item):
title = Field()
url = Field()
class StackSpider(Spider):
name = "stack"
allowed_domains = ["stackoverflow.com"]
start_urls = ["http://stackoverflow.com/questions?pagesize=50&sort=newest"]
def parse(self, response):
questions = Selector(response).xpath('//div[#class="summary"]/h3')
for question in questions:
item = StackItem()
item['title'] = question.xpath('a[#class="question-hyperlink"]/text()').extract()[0]
item['url'] = question.xpath('a[#class="question-hyperlink"]/#href').extract()[0]
yield item
if __name__ == '__main__':
settings = dict()
settings['USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
settings['ITEM_PIPELINES'] = {'JsonWriterPipeline': 1}
process = CrawlerProcess(settings=settings)
spider = StackSpider()
process.crawl(spider)
process.start()
As you see, the code is self contained and I override two settings; the USER_AGENT and the ITEM_PIPELINES. However when I set debug points in the JsonWriterPipeline class, I see that the code is executed and the debug points are never reached, thus the custom pipeline is not being used.
How can this be fixed?
I get 2 errors when running your script with scrapy 1.3.2 and Python 3.5.
First:
Unhandled error in Deferred:
2017-02-21 13:47:23 [twisted] CRITICAL: Unhandled error in Deferred:
2017-02-21 13:47:23 [twisted] CRITICAL:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/utils/misc.py", line 39, in load_object
dot = path.rindex('.')
ValueError: substring not found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/twisted/internet/defer.py", line 1301, in _inlineCallbacks
result = g.send(result)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/crawler.py", line 72, in crawl
self.engine = self._create_engine()
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/crawler.py", line 97, in _create_engine
return ExecutionEngine(self, lambda _: self.stop())
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/core/engine.py", line 70, in __init__
self.scraper = Scraper(crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/core/scraper.py", line 71, in __init__
self.itemproc = itemproc_cls.from_crawler(crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/middleware.py", line 58, in from_crawler
return cls.from_settings(crawler.settings, crawler)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/middleware.py", line 34, in from_settings
mwcls = load_object(clspath)
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/scrapy/utils/misc.py", line 41, in load_object
raise ValueError("Error loading object '%s': not a full path" % path)
ValueError: Error loading object 'JsonWriterPipeline': not a full path
You need to give a complete path for the pipeline. For example here, the __main__ namespace works:
settings['ITEM_PIPELINES'] = {'__main__.JsonWriterPipeline': 1}
Second (with this pipeline class fix above), you get loads of:
2017-02-21 13:47:52 [scrapy.core.scraper] ERROR: Error processing {'title': 'Apply Remote Commits to a Local Pull Request',
'url': '/questions/42367647/apply-remote-commits-to-a-local-pull-request'}
Traceback (most recent call last):
File "/home/paul/.virtualenvs/scrapy13.py3/lib/python3.5/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "test.py", line 20, in process_item
self.file.write(line)
TypeError: a bytes-like object is required, not 'str'
which you can fix with writing items JSON as bytes:
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line.encode('ascii'))
return item