我正试图从一个乐队的网站上删除Facebook帖子,但是我在搜索迭代的WebElement时遇到错误:
selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“class name”,“selector”:“userContent”}
找到的帖子成功,但搜索post_text_element时代码中断。我尝试用XPATH搜索,但结果是一样的。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
SITE_URL = 'https://www.facebook.com/pg/mnagaazdorp/posts/'
POSTS_XPATH = "//*[contains(@class, '_4-u2') and contains(@class, '_4-u8')]"
POST_TEXT_CLASS = "userContent"
TIMEOUT = 1
CHROME_DRIVER_PATH = "C:\\Users\\tonda\\Documents\\chromedriver.exe"
browser = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH)
browser.get(SITE_URL)
wait = WebDriverWait(browser, TIMEOUT)
posts = browser.find_elements_by_xpath(POSTS_XPATH)
for post in posts:
post_text_element = post.find_element_by_class_name(POST_TEXT_CLASS)
print(post_text_element.text)
browser.quit()
因此,post
是posts
数组的WebElement成员。语法
post.find_element_by_class_name(POST_TEXT_CLASS)
只有在匹配的元素是post
的直接子元素时才返回元素。点击你的链接并检查后,没有任何post
的直接孩子有一类userContent
。
但是,如果您尝试以下操作,您应该得到一个WebElements数组,其中包含为POSTS_XPATH
指定的xpath下面的所有div,它们具有userContent
类,我相信这是您的目标。如果以下内容有帮助,请告诉我:
posts = browser.find_elements_by_xpath("//*[contains(@class, '_4-u2') and contains(@class, '_4-u8')]//div[contains(@class, 'userContent')]")
然后,如果这是您的目标,您可以简单地遍历数组并打印每个帖子的文本。
for post in posts:
print(post.text)