如何正确执行xpath和条件查询?

时间:2019-07-31 15:09:46

标签: python selenium xpath amazon

我正在尝试在amazon.fr的主要选项上设置一个复选标记。

以下是链接(主要选项在左侧):https://www.amazon.fr/gp/browse.html?node=2036893031

以下是显示我要选中的字段的图像:https://ibb.co/ZY3mK3Z

我几乎可以正常工作了。但这不适用于所有亚马逊类别,这就是为什么我添加了“和”运算符。这是我的xpath查询:

function doGet(request) {
var htmlTemplate = HtmlService.createTemplateFromFile('formSubmitPage');
return htmlTemplate.evaluate();
}

function machineNameByCell(cellName) {
    var resinFormSubmitSheet = SpreadsheetApp.openById('1EmJMwV7AloL-Npb5Kz-d7WstEF0z-eqDzc5Bpk39x1o');
    var machineNameDataSheet = resinFormSubmitSheet.getSheetByName('machineName');
    var machineNameArray = [];
    for (var i = 1; i < 20; i++) {
        if (cellName == machineNameDataSheet.getRange(1, i).getValue()) {
            var j = 2;
            while (machineNameDataSheet.getRange(j, i).getValue() != "") {
                machineNameArray.push(machineNameDataSheet.getRange(j, i).getValue());
                j++;
            }
            break;
        }
    }
    this.machineNameArray = machineNameArray;
    return this;
}

function getData(helperName, cell, machine, batch, outOfResinTime) {
    var resinFormSubmitSheet = SpreadsheetApp.openById('1EmJMwV7AloL-Npb5Kz-d7WstEF0z-eqDzc5Bpk39x1o');
    var submitDataSheet = resinFormSubmitSheet.getSheetByName('resinReminderData');
    var lastUpdatedRow = submitDataSheet.getRange('A1:A').getLastRow();
    console.log(helperName);
    console.log(cell);
    console.log(machine);
    console.log(batch);
    console.log(outOfResinTime);
    submitDataSheet.getRange(lastUpdatedRow + 1, 1).setValue(helperName);
    submitDataSheet.getRange(lastUpdatedRow + 1, 2).setValue(cell);
    submitDataSheet.getRange(lastUpdatedRow + 1, 3).setValue(machine);
    submitDataSheet.getRange(lastUpdatedRow + 1, 4).setValue(batch);
    submitDataSheet.getRange(lastUpdatedRow + 1, 5).setValue(outOfResinTime);
}

如何正确设置查询格式?和运算符甚至是必需的吗?我收到以下错误消息:

  

TypeError:无法对“文档”执行“评估”:结果是   不是节点集,因此无法将其转换为所需的类型。

3 个答案:

答案 0 :(得分:3)

我认为您尝试单击而不传递WebElement。 您可以根据旁边的Prime标签的位置找到该复选框。

尝试以下xpath,

myprime = driver.find_element_by_xpath("//*[contains(@class,'icon-prime a-icon-small s-ref-text-link')]/parent::span/parent::label/input")
myprime.click();

答案 1 :(得分:0)

我刚刚尝试了下面的XPath,它位于元素的唯一位置

//label[.//i[contains(@class, 'a-icon-prime')]]/input
^ find a LABEL tag
       ^ that has a child I tag
            ^ that contains the class 'a-icon-prime' (indicating the prime logo)
                                               ^ then find an INPUT under the LABEL

答案 2 :(得分:0)

最小工作XPath locator为:

//i[contains(@class,'small') and contains(@class,'prime')]

为了获得更好的鲁棒性和可靠性,我建议将其包装到Explicit Wait中,例如:

prime = WebDriverWait(driver, 10).until(
    expected_conditions.presence_of_element_located((By.XPATH, "//i[contains(@class,'small') and contains(@class,'prime')]")))
prime.click()

更多信息:How to use Selenium to test web applications using AJAX technology