python硒无法找到子元素

时间:2019-06-22 02:22:37

标签: python selenium selenium-webdriver xpath css-selectors

我正在编写一个程序来迭代网页上的元素。我这样启动浏览器:

self.browser = webdriver.Chrome(executable_path="C:/Users/me/chromedriver.exe")
self.browser.get("https://www.google.com/maps/place/Foster+Street+Coffee/@36.0016436,-78.9018397,19z/data=!4m7!3m6!1s0x89ace473f05b7d39:0x42c63a92682d9ec3!8m2!3d36.0016427!4d-78.9012927!9m1!1b1")  

这将打开该站点,在其中可以找到我有兴趣使用的元素:

reviews = self.browser.find_elements_by_class_name("section-review-line")  

现在,我有一个类名“ section-review-line”的元素列表,该元素列表似乎正确填充。我想遍历此元素列表,并使用一组逻辑选择子元素。要获取子元素(我知道它以类名“ section-review-review-content”的形式存在),请尝试以下操作:

for review in reviews:
    content = review.find_element_by_class_name("section-review-review-content")  

出现以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".section-review-review-content"}

2 个答案:

答案 0 :(得分:0)

啊,想通了, 使用一个奇怪的页面,该页面的顶部有一个空元素,从而导致它出错。绝大多数元素都没有这个问题,使用try catch可以像这样解决它:

    reviews = self.browser.find_elements_by_class_name("section-review-line")
    for review in reviews:
        try:
            content = review.find_element_by_class_name("section-review-review-content")
            rtext = content.find_element_by_class_name("section-review-text").text
        except:
            continue

答案 1 :(得分:0)

好,这是您每次评论所需的所有物品信息。

reviews = driver.find_elements_by_class_name("section-review-content")
for review in reviews:
    reviewer = review.find_element_by_class_name("section-review-title").text
    numOfReviews = review.find_element_by_xpath(".//div[@class='section-review-subtitle']//span[contains(.,'reviews')]").text.strip().replace('.','')
    numberOfStarts = review.find_element_by_class_name("section-review-stars").get_attribute('aria-label').strip()
    publishDate = review.find_element_by_class_name("section-review-publish-date").text
    content = review.find_element_by_class_name("section-review-review-content").text