从 span 标签上方的文本节点获取文本

Get text from text node above span tag

下面是我尝试使用 python 和 selenium 抓取的一些 html。

<h2 class ="page-title">  
    Strange Video Titles
    <span class="duration">28 min</span>  
    <span class="video-hd-mark">720p</span> 
</h2> 

下面是我的代码:

title=driver.find_element_by_class_name('page-title').text
print(title)

但是,当我 运行 这样做时,它会打印 h2 标签内的所有内容,包括跨度 类 中的文本。我试图在末尾添加 [0] 或 [1] 以指定我只想要第一行文本,但这不起作用。如何只打印位于跨度 类?

上方的视频标题

编辑 - 我认为这是解决方案

所以我决定执行以下操作:

title=driver.find_element_by_class_name('page-title').text
duration = driver.find_element_by_xpath('/html/body/div/div[4]/h2/span[1]').text  
vid_quality =driver.find_element_by_xpath('/html/body/div/div[4]/h2/span[2]').text 


if (duration) in title:
    title = title.replace(duration, "")
if(vid_quality) in title:
    title = title.replace(vid_quality,"")

谢谢。

使用.contents

spam = """
<h2 class ="page-title">  
    Strange Video Titles
    <span class="duration">28 min</span>  
    <span class="video-hd-mark">720p</span> 
</h2>"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(spam, 'html.parser')
h2 = soup.find('h2')
print(h2.contents[0].strip())

# ALTERNATIVE -  remove the span tags
for span in h2.find_all('span'):
   span.decompose()
print(h2.text.strip())

输出

Strange Video Titles

使用WebDriverWait()并等待visibility_of_element_located()

使用JS executor并使用firstChild获取标题值

element=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"h2.page-title")))
print(driver.execute_script('return arguments[0].firstChild.textContent;', element))

您需要导入以下库

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

要仅打印视频标题,即 奇怪的视频标题,因为它是一个 文本节点,您必须引入 WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies :

  • 使用 XPATHget_attribute()splitlines():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[@class='page-title']"))).get_attribute("innerHTML").splitlines()[1])
    
  • 使用 CSS_SELECTORchildNodesstrip():

    print(driver.execute_script('return arguments[0].firstChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "h2.page-title")))).strip())
    
  • 注意:您必须添加以下导入:

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

参考资料

您可以在以下位置找到一些相关的详细讨论: