无头Chrome Puppeteer选择选项从下拉没有id

时间:2022-12-20 19:28:59

I'm using headless chrome with nodejs puppeteer library mostly. I'm having trouble selecting or clicking any options in a drop down. The problem is all the IDs are dynamic and change with every click. I've tried scraping the HTML and searching for the current id, but to no avail.

我主要使用带有nodejs puppeteer库的无头镀铬。我在下拉列表中选择或单击任何选项时遇到问题。问题是所有ID都是动态的,每次点击都会改变。我试过抓HTML并搜索当前的id,但无济于事。

Is there another way to select an option? Is it possible to use a different selector besides id?

有没有其他方法可以选择一个选项?是否可以使用除id之外的其他选择器?

无头Chrome Puppeteer选择选项从下拉没有id

note for image: where it says 'homeState-aria-id-7' the number 7 is dynamically generated

图片说明:在其中显示'homeState-aria-id-7'时,数字7是动态生成的

1 个解决方案

#1


0  

I'm not sure I am completely following the reason that having a dynamically created ID would cause issues. Here is an example with how I have solved the problem and using a selector for your code above.

我不确定我是否完全遵循动态创建ID会导致问题的原因。这是一个示例,说明我如何解决问题并为上面的代码使用选择器。

page.evaluate(optionSelector => {
    return document.querySelector(optionSelector).setAttribute('selected, 'true');
}, 'select[name="homeState"] > option[value="AL"]');

#1


0  

I'm not sure I am completely following the reason that having a dynamically created ID would cause issues. Here is an example with how I have solved the problem and using a selector for your code above.

我不确定我是否完全遵循动态创建ID会导致问题的原因。这是一个示例,说明我如何解决问题并为上面的代码使用选择器。

page.evaluate(optionSelector => {
    return document.querySelector(optionSelector).setAttribute('selected, 'true');
}, 'select[name="homeState"] > option[value="AL"]');