Webdriver:当类名包含空格时如何查找元素?

时间:2015-06-26 03:43:28

标签: python css python-2.7 selenium-webdriver webdriver

每个“7件装”搜索结果here包含多个评论,例如“5条评论”,没有评论“等。

每个的类名是fl r-iNTHbQvDybDU。它包含一个空格,所以如果我尝试find_elements_by_class_name(),我得到:

InvalidSelectorError: Compound class names not permitted

根据这里的其他答案,我需要做的就是移除空间并重试。没有运气 - 空名单

所以我尝试find_element_by_css_selector()

find_elements_by_css_selector(".fl.r-iNTHbQvDybDU")

仍然没有运气 - 空单。接下来你会尝试什么?

4 个答案:

答案 0 :(得分:2)

这个怎么样:

browser.find_elements_by_css_selector("div[class='fl r-iNTHbQvDybDU']")

这假定为class = div

的标记

如果是其他的话 - 否则用适当的标签替换div ..

答案 1 :(得分:1)

试试这个:

find_elements_by_css_selector(".r-iNTHbQvDybDU")

答案 2 :(得分:1)

我不会依赖这些自动生成的类名。除了不可靠之外,它还会降低您的代码的可读性。相反,请获取包含“审核”文本的链接

Webdriver/Selenium: How to find element when it has no class name, id, or css selecector?主题的组合解决方案:

import re

from selenium.common.exceptions import NoSuchElementException    
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver


driver = webdriver.Chrome()
driver.get('https://www.google.com/?gws_rd=ssl#q=plumbers%2BAvondale%2BAZ')

# waiting for results to load
wait = WebDriverWait(driver, 10)
box = wait.until(EC.visibility_of_element_located((By.ID, "lclbox")))

phone_re = re.compile(r"\(\d{3}\) \d{3}-\d{4}")

for result in box.find_elements_by_class_name("intrlu"):
    for span in result.find_elements_by_tag_name("span"):
        if phone_re.search(span.text):
            parent = span.find_element_by_xpath("../..")
            print parent.text
            break

    try:
        reviews = result.find_element_by_partial_link_text("review").text
    except NoSuchElementException:
        reviews = "0 Google reviews"

    print reviews
    print "-----"

打印:

360 N Central Ave
Avondale, AZ
(623) 455-6605
1 Google review
-----
Avondale, AZ
(623) 329-5170
4 Google reviews
-----
Tolleson, AZ
(623) 207-1995
7 Google reviews
-----
3947 N 146th Dr
Goodyear, AZ
(602) 446-6576
1 Google review
-----
564 W Western Ave
Goodyear, AZ
(623) 455-6605
0 Google reviews
-----
14190 W Van Buren St
Goodyear, AZ
(623) 932-5300
0 Google reviews
-----

答案 3 :(得分:0)

你需要在它前面添加标签名称。

例如,它位于div元素内,然后:

Selenium.find_element_by_class_name(div.ur.class.name)