简体   繁体   English

在python中使用Selenium定位Web元素

[英]Locating web element using selenium in python

I am trying to find an element in the web page using selenium. 我正在尝试使用硒在网页中查找元素。 when I "right click" on the web element and inspect, I can find the html code in the console. 当我在Web元素上“右键单击”并检查时,我可以在控制台中找到html代码。 However when I copy the xpath of the same element from the console and try to execute it in firepath, it says "No matching nodes". 但是,当我从控制台复制同一元素的xpath并尝试在firepath中执行它时,它显示“没有匹配的节点”。 Why is it so and how can I fix this ? 为什么会这样,我该如何解决?

Here is the HTML of the element. 这是元素的HTML。

<input id="mobile" type="text" onchange="javascript:dispLocMob(this);
"onkeydown="javascript:dispLocMob(this);
"onkeyup="javascript:dispLocMob(this);" value="" maxlength=
"10" placeholder="Mobile Number" name="mobile">

And this is what I am doing: 这就是我在做什么:

receiverMobileElement = browser.find_element_by_xpath('//*[@id="mobile"]')

Please help. 请帮忙。

Why using xpath when you can find the element by unique id ? 当您可以通过唯一 id查找元素时,为什么要使用xpath

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://example.com')

target_element = browser.find_element_by_id('mobile')

I always say screw firebug, use the Chrome console.. 我总是说螺丝萤火虫,请使用Chrome控制台。

From the looks of it, the best way to get this particular element would be one of the following two options (given that 'id=mobile' is unique).. 从外观上看,获取此特定元素的最佳方法是以下两个选项之一(假设'id = mobile'是唯一的)。

By.cssSelector("#mobile");
By.xpath("//input[@id = 'mobile']");

To use the chrome console --> 要使用Chrome控制台->

  1. Start Chrome 启动Chrome
  2. Right click and inspect your element. 右键单击并检查您的元素。
  3. You should see the html code and the console appear below it. 您应该看到html代码,控制台出现在其下方。 (If you can not see the console, click the three vertical dots and select 'Show Console' (如果看不到控制台,请点击三个垂直点,然后选择“显示控制台”
  4. Now, from here you can do some awesome stuff! 现在,从这里您可以做一些很棒的事情! You can search for the elements that you are trying to identify and see if they can be found. 您可以搜索要识别的元素,然后查看是否可以找到它们。 for example, to see if the By.cssSelector("#mobile"); 例如,查看By.cssSelector(“#mobile”); will work type this 可以输入这个

document.querySelectorAll("#mobile") document.querySelectorAll( “#移动”)

for the xpath, type this 对于xpath,请输入

$xBy.xpath("//input[@id = 'mobile']"); $ xBy.xpath(“ // input [@id ='mobile']”);

Just a suggestion... dont be concerned about firebug if your code works, and seriously try out this way in chrome!! 只是一个建议...如果您的代码有效,请不要担心萤火虫,并认真尝试在chrome中尝试这种方式!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM