下面是一些我正在尝试使用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标记中的所有内容,包括span类中的文本。我尝试在末尾添加或添加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,"")谢谢。
发布于 2020-11-11 18:10:06
使用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 WebDriverWaithttps://stackoverflow.com/questions/64789848
复制相似问题