如何找到元素硒

时间:2015-12-01 04:21:46

标签: python selenium xpath

我如何找到

 element = driver.find_element_by_id("id","class","class")

我试图点击广告 直接使用xpath不起作用:

/html/body/div/div[1]/div[1]/div/a/img

Traceback (most recent call last):
File "a.py", line 14, in <module>
element = driver.find_element_by_id("/html/body/div/div[1]/div[1]/div/a/img")

HTML如下所示:

</head> 
<body scroll="no">
   <div id="widget" class="widget">
   <div class="plug">
   <div class="thumbBorder">
   <div class="thumb">
   <div class="ton" style="display: block;">
      <div class="title_bg"> </div>
      <a class="title q" target="_blank" href="//prwidgets.com/t/ghxa/g0us/7433c239e19107a4301ad9959d2d37440/aHR0cDovL3Ry‌​aXBsZXh2aWQuY29tLw==">Kiss N Tell</a> 
   </div>
   <a class="q" target="_blank" href="//prwidgets.com/t/ghxa/g0us/7433c239e19107a4301ad9959d2d37440/aHR0cDovL3Ry‌​aXBsZXh2aWQuY29tLw=="> <img title="Title" src="//prstatics.com/prplugs/0/747604/160x120.jpg"

3 个答案:

答案 0 :(得分:1)

Selenium中的

find_element_by_id python绑定接受一个参数,该参数是id属性的值。如 login_form = driver.find_element_by_id('loginForm') 请参阅文档here 除此之外,你可以使用

driver.find_element(By.ID, 'your ID')

答案 1 :(得分:1)

在这种情况下,您可以尝试xpath - 和axis,即following-sibling

element = driver.find_element_by_xpath("//a[class='q']/following-sibling::img[1]")
element.click()

N.B我假设整个html文件中没有a类名q

答案 2 :(得分:1)

这可能不适合你,但是当没有一个简单的ID或NAME可以抓取时,我进入浏览器(我将参考Firefox)右键单击该元素,选择&#39; Inspect Element&#39; ,然后右键单击检查窗口中突出显示的区域,并选择“复制唯一选择器”#39;。然后您可以将其粘贴到您的代码中并使用:

selector = 'pasted string here'
element = driver.find_element_by_css_selector(selector) 
element.click()

编辑:使用以下@James提供的选择器:

selector = 'div.plug:nth-child(1) > div:nth-child(1) > div:nth-child(1) > a:nth-child(2) > img:nth-child(1)'
element = driver.find_element_by_css_selector(selector)
element.click()

这通常对我有用。

编辑:添加一个真实的例子。试试这个,看它是否有效。

# open google search page and click the "About" link

from selenium import webdriver

driver = webdriver.Firefox()
driver.maximize_window()
driver.get('www.google.com/ncr')
# got the selector below using Firefox 'Inspect Element -> Copy Unique Selector'
about_selector = 'a._Gs:nth-child(3)' 
about = driver.find_element_by_css_selector(about_selector)
about.click()