1

xpath と Java を使用して html を解析するコードをいくつか書きました。html ファイルは次のようなものです。

    <div class="field_row">
    <label for="names">Names *</label>
    <input id="address.A" type="text" maxlength="15" size="32" value="12345" name="address.work">
    <span class="additional_info"> Information 1 </span>
    </div>
    <div class="field_row">
    <label for="names">Names *</label>
    <input id="address.B" type="text" maxlength="15" size="32" value="12345" name="address.work">
    <span class="additional_info"> Information 2 </span>
    </div>

そして Java コード:

    public static final Element INFOFIELD= Element.findXPath(".//*[@class='additional_info'");

「情報 1」を取得させてくれます。ただし、「情報 2」を取得する必要があります。したがって、私は使用します:

    public static final Element INFOFIELD= Element.findXPath(".//*[@class='additional_info' and @id='address.B']");

しかし、エラーが発生しました。ヒントを教えてください。ありがとう。A.

4

1 に答える 1

0

You can create an XPath based on your input field (address.B), and then specify you want to access one of its sibling nodes and thus retrieve its data...

XPath:

//input[@id='address.B']/following-sibling::span[@class='additional_info']

as you can see after we find the input node with the id attribute 'address.b', we specify 'following-sibling'. This indicates that we want to select one of the siblings after the current node('address.B's input field). Then we specify which node that is followed by the attribute details: span[@class='additional_info']

some working code implementing the above XPath:

WebElement element = driver.findElement(By.xpath("//input[@id='address.B']/following-sibling::span[@class='additional_info']"));
System.out.println(element.getText());

will print 'Information 2'

You can use XPath axes in other related ways to access other nodes in the DOM (parents, children, siblings,etc).

http://www.w3schools.com/xpath/xpath_axes.asp

An axis defines a node-set relative to the current node.
于 2013-10-17T11:32:51.213 に答える