如何使用Python中的Playwright查找包含特定单词的多个ID?

huangapple go评论89阅读模式
英文:

How do I find multuple IDs that contain a specific word using Playwright in python?

问题

我正在尝试学习Python版本的Playwright,

我如何通过它们的ID的一部分来定位多个元素,然后继续点击它们?
例如,
页面上的第一个元素的ID为"id="railRadio_420""",第二个元素的ID为"id="railRadio_421""",第三个元素的ID为"id="railRadio_422""",依此类推,最后一个元素的ID为"id="railRadio_424""

如上所示,ID是连续的,但存在两个问题。

  • 第一个问题是,第一个元素的起始数字每次都是随机的,所以我们不知道三位数是多少 -> id="railRadio_XXX"
  • 第二个问题是,我们不知道有多少个ID,所以例如序列可以从ID编号421到424或421到426,

是否有一种方法可以找出有多少个ID以及ID号码是什么,以便我可以点击它们中的每一个?

我尝试制作一个循环,点击所有ID

    startingNumber = 432
    for i in range(5):
        railRadio_X = 'railRadio_' + str(startingNumber)
        page.click('[id=' + railRadio_X + ']')
        startingNumber += 1

问题是我不知道起始数字是多少,也不知道有多少个ID。
有什么办法可以通过检查它们是否包含文本"railRadio_"来定位ID,使用Playwright?

英文:

I'm trying to learn the Python version of Playwright,

How do I locate multiple elements partially by their ID, and then proceed to click on them?
For example,
the first element in the page has the ID of "id="railRadio_420"", the second one has "id="railRadio_421"", the third one has "id="railRadio_422"", etc...., the last element has the ID of id="railRadio_424"

The IDs are sequential as seen above, but there are 2 issues.

  • The first issue is that the first element has a random starting number each time so we don't know what are the three digits -> id="railRadio_XXX"
  • The second issue is that we don't know how many IDs there are in the first place, so for example the sequence could be from ID number 421 to 424 or 421 to 426,

Is there a way where I can find how many IDs there are and what the ID numbers are so I can click on each one of them?

I tried to make a loop that clicks through all the IDs

    startingNumber = 432
    for i in range(5):
        railRadio_X = 'railRadio_' + str(startingNumber)
        page.click('[id='+ railRadio_X +']')
        train_nmb +=1

The issue is that I don't know what the starting number is and don't know how many IDs there are.
Any ideas how can I locate the IDs by checking if they contain the text "railRadio_" using Playwright?

答案1

得分: 1

不使用循环,可以这样做:

all = page.query_selector_all('*[id*="railRadio"]')
for item in all:
    item.click()

当使用星号(*)时,表示你正在搜索部分匹配的内容。所有包含短语 "railRadio" 的 ID 都会被找到。你可以遍历它们并单击每一个。

英文:

Instead of using a loop, do this:

all = page.query_selector_all('*[id*="railRadio"]')
        for item in all:
            item.click()

When you use Asterisk (*) it means that you are searching for a partial match. All the IDs that contain the phrase "railRadio" will be found. You will be able to iterate over them and click each one.

huangapple
  • 本文由 发表于 2023年3月7日 23:06:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定