如何使用Selenium/Python提取嵌套多子div的父div中的目标注释文本
解决方案
方案1:直接通过DOM节点提取(推荐,稳定性更高)
你要的目标内容是外层<div data-testid="comment">的直接文本节点,不属于任何子div,不需要解析整个文本内容,直接通过JS执行就能拿到,不受标题、日期、末尾可选内容的变化影响,稳定性远高于正则方案:
try: element = WebDriverWait(driver, 40).until( EC.element_to_be_clickable((By.XPATH, xpathCommentPage))) comments = driver.find_elements_by_xpath(realtiveXpathToReportComments) # 直接遍历父div的直接子节点,提取第一个非空文本节点 target_comment = driver.execute_script(""" const childNodes = arguments[0].childNodes; for (let node of childNodes) { if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') { return node.textContent.trim(); } } return ''; """, comments[0]) print(target_comment) except: print("could not find comments on comment page")
方案2:正则表达式实现(适合已经拿到完整innerText的场景)
如果你不想修改原有获取逻辑,已经拿到了完整的innerText字符串,也可以通过正则提取,逻辑是跳过前两行固定的标题、日期,捕获后续内容直到末尾可选注释之前:
import re try: element = WebDriverWait(driver, 40).until( EC.element_to_be_clickable((By.XPATH, xpathCommentPage))) comments = driver.find_elements_by_xpath(realtiveXpathToReportComments) comment = comments[0].get_attribute("innerText") # 正则适配目标注释多行、末尾可选注释不存在的场景 match = re.match(r'^.*\n.*\n([\s\S]*?)(?:\n[^\n]*)?$', comment) if match: target_comment = match.group(1).strip() print(target_comment) except: print("could not find comments on comment page")
内容的提问来源于stack exchange,提问作者AppCreator
相关产品推荐
相关产品推荐

