如何在casperJs中设置输入标记的值

问题描述 投票:23回答:2

我有输入元素如图所示:

<input type="text" class="bg-white" id="couponCode" value="">

如何使用casperJs设置/填充其值

web-scraping phantomjs casperjs
2个回答
41
投票

0
投票

有几种不同的方法可用于完成此任务。

除非您需要执行更复杂的操作,否则您应该使用casper.sendKeys()


casper.sendKeys():

如果您想设置CasperJS环境中的值,并且input元素可选择在form元素中,那么您可以使用casper.sendKeys()

casper.sendKeys('#couponCode', 'Hello, world!');

casper.fill():

如果您想设置CasperJS环境中的值,并且input元素位于form元素内,并且包含name属性,那么您可以使用casper.fill()

casper.fill('#form', {
  couponCode: 'Hello, world!', // #form [name="couponCode"]
});

casper.fillSelectors():

如果你想设置CasperJS环境中的值,并且input元素在form元素中,并且你想使用CSS3选择器引用input元素,那么你可以使用casper.fillSelectors()

casper.fillSelectors('#form', {
  '#couponCode': 'Hello, world!', // #form #couponCode
});

casper.fillLabels():

如果您想设置CasperJS环境中的值,并且input元素位于form元素内,并且包含带有文本的关联label元素,那么您可以使用casper.fillLabels()

casper.fillLabels('#form', {
  couponCode: 'Hello, world!', // #form label[text()="couponCode"] input
});

casper.fillXPath():

如果您想设置CasperJS环境中的值,并且input元素位于form元素内,并且您想使用XPath选择器引用input元素,那么您可以使用casper.fillXPath()

casper.fillXPath('#form', {
  '//*[@id="couponCode"]': 'Hello, world!', // #form #couponCode
});

casper.evaluate():

如果您想设置Page DOM环境中的值,并且input元素可选择在form元素中,那么您可以使用casper.evaluate()

casper.evaluate(function () {
  document.getElementById('couponCode').value = 'Hello, world!';
});

注意:与evaluate()类似,您也可以使用:evaluateOrDie()thenEvaluate()thenOpenAndEvaluate()(如果您希望一次完成两个或多个与正在执行的步骤相关的操作)。

© www.soinside.com 2019 - 2024. All rights reserved.