1

I'm trying to automate the Google Translate web interface with Selenium (but it's not necessary to understand Selenium to understand this question, just know that it finds elements and clicks them). I'm stuck on selecting the language to translate from.

I can't get to the point where the drop-down menu opens, as seen in the screenshot below.

Now, I want to select 'Japanese'.

This xpath expression works: $b.find_element(:xpath,"//*[@id=':13']/div").click But I would rather have one where I can just input the name of the language.

This xpath expression also works: $b.find_element(:xpath,"//*[contains(text(),'Japanese')]").click But only as long as there is no other 'Japanese' text on the page.

So I'm trying to narrow down the scope of my xpath, but when I try to specify the path to take to find the 'Japanese' text, the expression no longer works, I can't find the element: $b.find_element(:xpath,"//*div[@id='gt-sl-gms']/*[contains(text(),'Japanese')]").click

It also no longer works for the original xpath either: $b.find_element(:xpath,"//*div[@id='gt-sl-gms']/*[@id=':13']/div").click Which is weird, because to bring down the drop-down menu, I use this xpath $b.find_element(:xpath,"//*[@id='gt-sl-gms']/*[contains(text(),'From:')]").click.

So it's not that I have two wildcards in my expression and it's not that my expression is too specific. There's something else that I'm missing and I'm sure it's really simple.

Any suggestions are appreciated.

Edit Other things I have tried unsuccessfully:

$b.find_element(:xpath,"//*/div[@id='gt-sl-gms']/*[@id=':13']/div").click $b.find_element(:xpath,"//*[@id='gt-sl-gms']/*[@id=':13']/div").click $b.find_element(:xpath,"//*[@id='gt-sl-gms']//*[@id=':13']/div").click

4

3 回答 3

2

尝试选择后代 (//) 而不是 (/*) 真正的孙子或更深。

于 2013-05-28T02:05:06.403 回答
2

如果带有“@id=':13'”的 div 是 带有“@id='gt-sl-gms”的 div 的后代,那么您的 xpaht"//*[@id='gt-sl-gms']//*[@id=':13']/div"就可以了。上面的 xpaht 期望 html 看起来像:

<div id="gt-sl-gms">
    <div>
        <div id=":13">
            <div></div>
        </div>
    </div>
</div>

如果<div id="gt-sl-gms">不是一个祖先(如我所料),你必须寻找一个“真正的”祖先,或者你可以使用跟随(用于文档中稍后的节点)或跟随兄弟(用于文档中稍后在同一级别的节点以前的。

于 2013-05-28T05:42:54.297 回答
2

*div是不正确的,应该只是div。此外,根据 HTML 的结构,您可能需要//代替/.

于 2013-05-28T02:03:08.577 回答