看板 Python 關於我們 聯絡資訊
我現在用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
ides13: 將所有的format編寫成字典,然後用key調用?Dpath[key]. 05/04 11:38
jacobcan118: 不過我很多需要format的時候都是變數在跑降可以編成 05/04 19:40
jacobcan118: 字典嗎 05/04 19:40
ides13: 我不確定,但將format編成字典是cookbook中的例子內的作法 05/04 21:48
ides13: http://tinyurl.com/kuaou94。指定變數字符串。 05/04 22:00
jacobcan118: 我已經在字符串中插入變量了. 但是還是會有很多情形 05/05 11:38
jacobcan118: 像是我想要找在pageA裡elemetnA下的elementB會變成 05/05 11:39
jacobcan118: locator = '{}/{}'.format(PageA.pageAelementA.valu 05/05 11:40
jacobcan118: e.format(xxx), PageA.pageAelementB.value.format(x 05/05 11:41
zerof: 如果都是用 Enum.value 的話改用 namedtuple 會比較好 05/05 11:53
zerof: sample code: https://repl.it/Hhja/1 05/05 12:32
jacobcan118: 感謝 學了一下namedtuple 如果我每一個class 只給值 05/11 07:28
jacobcan118: 一次 有人降用嗎 05/11 07:28
zerof: 跟你用 Enum 的概念是一樣的吧...... 05/11 10:55
ides13: https://youtu.be/mWB3oh1GPdo?t=191 05/11 18:03
ides13: Avoid overengineering datastructures. 05/11 18:04
ides13: Tuples are better than objects (try namdtuple too 05/11 18:05
ides13: too though).Prefer simple fields over getter/setter fn 05/11 18:06