[問題] Enum建立大量的字串

看板Python作者 (jacobcan118)時間8年前 (2017/05/04 10:18), 編輯推噓4(4014)
留言18則, 3人參與, 最新討論串1/1
我現在用python去讀大量的對應變數來跑selenium頁面測試.每個頁面的element都有對應的字串, 我想用python 的Enum去建一個檔大概像下面一樣. file: ElementEnum.py from enum import Enum class PageA(Enum): pageAelementA = '//div[{}]/a' pageAelementB = '//button[.="{}"]' pageAelementC = '//tr[{}]/td[{}]' class PageC(Enum): pageBelementA = '//div[{}]/a' pageBelementB = '//button[.="{}"]' pageBelementC = '//tr[{}]/td[{}]' class PageB(Enum): pageCelementA = '//div[{}]/a' pageCelementB = '//button[.="{}"]' pageCelementC = '//tr[{}]/td[{}]' 但之後在用後, 發現常常需要用format去建完整的字串變成可讀的xpath或是css selector字串.想請問大家有沒有比較好的建議, 因為當我在建locator有很多需要format的地方會看起來很雜亂 import ElementEnum.PageA as PA driver.find_element_by_xpath('{}//table/thead[{}]'.format(PA.pageAelementA.value, 1)) func(index, **kwargs): driver.find_element_by_xpath('//table/thead[{}]/tr[{}]/td[{}]/{}'.format(index, kwargs['row'], kwargs['col'], PA.pageBelementA.value)) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 108.14.0.213 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1493864315.A.4A6.html

05/04 11:38, , 1F
將所有的format編寫成字典,然後用key調用?Dpath[key].
05/04 11:38, 1F

05/04 19:40, , 2F
不過我很多需要format的時候都是變數在跑降可以編成
05/04 19:40, 2F

05/04 19:40, , 3F
字典嗎
05/04 19:40, 3F

05/04 21:48, , 4F
我不確定,但將format編成字典是cookbook中的例子內的作法
05/04 21:48, 4F

05/04 22:00, , 5F
http://tinyurl.com/kuaou94。指定變數字符串。
05/04 22:00, 5F

05/05 11:38, , 6F
我已經在字符串中插入變量了. 但是還是會有很多情形
05/05 11:38, 6F

05/05 11:39, , 7F
像是我想要找在pageA裡elemetnA下的elementB會變成
05/05 11:39, 7F

05/05 11:40, , 8F
locator = '{}/{}'.format(PageA.pageAelementA.valu
05/05 11:40, 8F

05/05 11:41, , 9F
e.format(xxx), PageA.pageAelementB.value.format(x
05/05 11:41, 9F

05/05 11:53, , 10F
如果都是用 Enum.value 的話改用 namedtuple 會比較好
05/05 11:53, 10F

05/05 12:32, , 11F
05/05 12:32, 11F

05/11 07:28, , 12F
感謝 學了一下namedtuple 如果我每一個class 只給值
05/11 07:28, 12F

05/11 07:28, , 13F
一次 有人降用嗎
05/11 07:28, 13F

05/11 10:55, , 14F
跟你用 Enum 的概念是一樣的吧......
05/11 10:55, 14F

05/11 18:03, , 15F

05/11 18:04, , 16F
Avoid overengineering datastructures.
05/11 18:04, 16F

05/11 18:05, , 17F
Tuples are better than objects (try namdtuple too
05/11 18:05, 17F

05/11 18:06, , 18F
too though).Prefer simple fields over getter/setter fn
05/11 18:06, 18F
文章代碼(AID): #1P2ezxIc (Python)