小编ale*_*cxe的帖子

python xml.etree.ElementTree附加到子元素

我正在尝试使用xml.etree.ElementTree来解析xml文件,查找特定标记,将子项附加到该标记,将另一个子项附加到新创建的标记并将文本添加到后一个子项.

我的XML:

<root>
<a>
    <b>
      <c>text1</c>
    </b>
    <b>
      <c>text2</c>
   </b>
</a>
</root>    
Run Code Online (Sandbox Code Playgroud)

期望的XML:

<root>
<a>
    <b>
      <c>text1</c>
    </b>
    <b>
      <c>text2</c>
   </b>
    <b>
      <c>text3</c>
   </b>
</a>
</root>
Run Code Online (Sandbox Code Playgroud)

当前代码:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()


for x in root.iter():
    if (x.tag == 'a'):
        ET.SubElement(x, 'b')
        ET.SubElement(x, 'c')
        #add text
Run Code Online (Sandbox Code Playgroud)

这似乎有效,除了'c'作为'a'而不是'b'的孩子.

像这样:

<root>
<a>
    <b>
      <c>test1</c>
    </b>
    <b>
      <c>test2</c>
    </b>
  <b /><c/></a>
</root>
Run Code Online (Sandbox Code Playgroud)

另外,如何将文本添加到新创建的元素"c"中?我可以迭代直到找到没有文字的标签'c',但必须有更好的方法.

python xml elementtree xml-parsing

8
推荐指数
1
解决办法
2万
查看次数

在PyPy下使用__slots__

我有这个简单的代码帮助我测量类的__slots__执行方式(从这里开始):

import timeit

def test_slots():
    class Obj(object):
        __slots__ = ('i', 'l')

        def __init__(self, i):
            self.i = i
            self.l = []

    for i in xrange(1000):
        Obj(i)

print timeit.Timer('test_slots()', 'from __main__ import test_slots').timeit(10000)
Run Code Online (Sandbox Code Playgroud)

如果我通过python2.7运行它 - 我会在6秒左右得到一些东西 - 好吧,它比没有插槽时更快(并且内存效率更高).

但是,如果我在PyPy下运行代码(使用2.2.1 - 64位用于Mac OS/X),它开始使用100%CPU并且"从不"返回(等待几分钟 - 没有结果).

到底是怎么回事?我应该__slots__在PyPy下使用吗?

如果我传递不同的数字,会发生什么timeit():

timeit(10) - 0.067s
timeit(100) - 0.5s
timeit(1000) - 19.5s
timeit(10000) - ? (probably more than a Game of Thrones episode)
Run Code Online (Sandbox Code Playgroud)

提前致谢.


请注意,如果我使用namedtuples,则会观察到相同的行为:

import collections
import timeit …
Run Code Online (Sandbox Code Playgroud)

python performance pypy slots

8
推荐指数
2
解决办法
868
查看次数

点正则表达式搜索

我需要找到PyPI匹配特定正则表达式的所有包:

^django-.*?admin.*$
Run Code Online (Sandbox Code Playgroud)

基本上,包的名字应该与启动django-,并有admin后话.例如,以下包应该匹配:

django-redis-admin
django-admin-ckeditor 
django-admintools-bootstrap
Run Code Online (Sandbox Code Playgroud)

我能做到pip search django-,但是有很多我不感兴趣的软件包.

是否pip提供了一种通过正则表达式查找包的方法?或者,我应该只是管的结果django-,以grep过滤掉无关的包?

此外,可能是一个的"交集" pip search django-,并pip search admin有助于太.

python regex packages pip

8
推荐指数
1
解决办法
2291
查看次数

Python unittest忽略了numpy

我正在使用unittest编写python测试并从命令行运行测试

 nosetests --with-coverage -x
Run Code Online (Sandbox Code Playgroud)

当我在我的一个测试中包含numpy时,它也试图测试numpy包.示例输出:

...
Name                            Stmts   Miss  Cover   Missing
-------------------------------------------------------------
CLOCK                              39     33    15%   3, 7-13, 17, 20-25, 28-47
LFU                                42      1    98%   52
LRU                                95      9    91%   12, 64, 68, 101, 115-118, 131
LRU10                              54      1    98%   68
LRU3                               54      1    98%   68
argparse                         1177   1177     0%   3-2361
cache                              86     33    62%   36-47, 86-89, 95-116
common                             87     54    38%   17, 20, 23, 28, 31-32, 35-36, 39, 42, 46, 48, 50, 52, 54, 57-64, 67-68, 72-89, 95-96, 102-107, …
Run Code Online (Sandbox Code Playgroud)

python unit-testing numpy nosetests python-unittest

8
推荐指数
1
解决办法
1008
查看次数

Python Selenium获取当前窗口句柄

Selenium for Java和Ruby有方法来获取当前窗口句柄.

例如,在Java中,它指向了这里.

同时Pythonic版本的Selenium没有这样的方法.

  1. 也许它在里面,但我没有看到它?
  2. 如果它被跳过,是否合理以及如何为它做出解决方法?

python selenium selenium-webdriver

8
推荐指数
1
解决办法
1万
查看次数

selenium move_to_element并不总是鼠标悬停

我正在使用python 2.7.在尝试将鼠标悬停在菜单项上时,selenium不会在Chrome中始终将鼠标移动到该项目.因此,在单击子菜单时,它最终会单击其他内容.但是,相同的代码会在Firefox驱动程序中抛出异常.

我读了几篇关于SO的帖子,这些帖子表明硒有时候很古怪.但我无法弄清楚我是否做错了什么.

这是代码:

from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
#driver = webdriver.Firefox()
driver.get("http://www.flipkart.com/watches/pr?p%5B%5D=facets.ideal_for%255B%255D%3DMen&p%5B%5D=sort%3Dpopularity&sid=r18&facetOrder%5B%5D=ideal_for&otracker=ch_vn_watches_men_nav_catergorylinks_0_AllBrands")
driver.maximize_window()
sleep(10)

elm_Men_Menu = driver.find_element_by_xpath("//li[@class='menu-l0 ']/a[@data-tracking-id='men']")
elm_FastTrack_Menu = driver.find_element_by_xpath("//li[@class='menu-item']/a[@data-tracking- id='0_Fastrack']")

builder = ActionChains(driver)
builder.move_to_element(elm_Men_Menu).click(elm_FastTrack_Menu).perform()
Run Code Online (Sandbox Code Playgroud)

python selenium google-chrome python-2.7 selenium-webdriver

8
推荐指数
1
解决办法
2万
查看次数

量角器返回一个对象但是期望 - element.getText()的值

无法理解为什么它返回一个对象而不是文本值,一些测试代码:

describe('columns swap', function () {

    describe('location column ', function () {
        it('should swap right', function () {
            browser.sleep(10000);
            var fColumn = element(by.xpath('(//*[@class="k-link"])[2]')).getText();
            console.log(fColumn); 
Run Code Online (Sandbox Code Playgroud)

控制台输出:

>   columns swap
>     location column { ptor_:    { controlFlow: [Function],
>      schedule: [Function],
>      getSession: [Function],
>      getCapabilities: [Function],
>      quit: [Function],
>      actions: [Function],
>      executeScript: [Function],
>      executeAsyncScript: [Function],
>      call: [Function],
>      wait: [Function],
>      sleep: [Function],
>      getWindowHandle: [Function],
>      getAllWindowHandles: [Function],
>      getPageSource: [Function],
>      close: [Function],
>      getCurrentUrl: …
Run Code Online (Sandbox Code Playgroud)

javascript end-to-end promise selenium-webdriver protractor

8
推荐指数
1
解决办法
8475
查看次数

如何测试django模型方法__str __()

我试图测试__str__方法,当我尝试在我的测试中访问它时,它返回我的模型实例(我认为它是)

def test_str_is_equal_to_title(self):
    """
    Method `__str__` should be equal to field `title`
    """
    work = Work.objects.get(pk=1)
    self.assertEqual(work.__str__, work.title)
Run Code Online (Sandbox Code Playgroud)

从测试我得到:

AssertionError: '<bound method Work.__str__ of <Work: Test title>>' != 'Test title'
Run Code Online (Sandbox Code Playgroud)

我应该如何比较这两个值来通过测试?

python testing django django-models

8
推荐指数
1
解决办法
4203
查看次数

无法再打开和关闭Chrome中的标签页

问题:

几个月前,我们为多标签功能添加了一个测试,打开标签,CTRL/COMMAND + tCTRL/COMMAND + v键盘快捷键关闭.

相关助手功能:

this.getControlKey = function () {
    var isWin = /^win/.test(process.platform);
    return isWin ? protractor.Key.CONTROL : protractor.Key.COMMAND;
};

this.openAndSwitchToNewTab = function (url) {
    element(by.tagName("body")).sendKeys(protractor.Key.chord(this.getControlKey(), "t"));

    // failing, if new tab was not opened
    browser.getAllWindowHandles().then(function (handles) {
        expect(handles.length).toBeGreaterThan(1);
    });

    return browser.get(url);
};
Run Code Online (Sandbox Code Playgroud)

最近,它开始失败并出现Expected 1 to be greater than 1错误,这意味着未打开新选项卡.并且,我已经确认两个键盘快捷键都不再起作用了.

为什么用快捷键停止打开和关闭标签?

使用当前最新的Protractor 2.1.0和ChromeDriver 2.15(也尝试了最新的2.16,没有运气).


想法和更多信息:

  1. 起初,我认为这是与Chrome 44相关的问题:

    但是,使用BrowserStack我已经在旧版Chrome上重现了这个问题.

  2. 它在Firefox中像发条一样工作.

  3. 我实际上可以看到发送到body日志中元素的和弦BrowserStack,但浏览器中没有任何反应.
  4. 我实际上可以在Windows上使相同的代码工作.所以,它可能是Mac …

javascript selenium google-chrome selenium-webdriver protractor

8
推荐指数
1
解决办法
1153
查看次数

Webdriver管理更新错误

我是新手使用量角器.尝试安装独立webdriver-manager但出现以下错误.

Node v7.2.0
Protractor 5.0.0
webdriver-manager 11.1.1
Run Code Online (Sandbox Code Playgroud)

当我跑步时,webdriver-manger update --standalone我得到以下错误

[17:25:21] I/file_manager - creating folder C:\Users\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium
[17:25:22] E/downloader - undefined
[17:25:22] I/update - chromedriver: file exists C:\Users\AppData\Roaming\npm\node_modules\protractor\node_modules\webdriver-manager\selenium\chromedriver_2.26win32.zip
[17:25:22] I/update - chromedriver: unzipping chromedriver_2.26win32.zip
**(node:14972) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Invalid filename
(node:14972) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[17:25:22] E/downloader - undefined
[17:25:22] I/update - …
Run Code Online (Sandbox Code Playgroud)

selenium node.js protractor webdriver-manager

8
推荐指数
1
解决办法
4516
查看次数