我用 python 和 selenium 制作了一個腳本,可以在 youtube 上進行搜索。當它完全加載時,我只能從結果中獲取所有標題。有沒有我可以集成的代碼行來獲取日期發布?
這是我的代碼:
def youTube():
term = 'bitcoin'
tit = []
d = webdriver.Firefox()
d.get('https://www.youtube.com/results?search_query=' term '&sp=CAISAhAB')
sleep(3)
d.find_element_by_xpath("//*[contains(text(), 'Accetto')]").click()
sleep(2)
scrollHeight = d.execute_script("return window.scrollMaxY")
print(scrollHeight)
scrolled_pages = 0
# while we have not reached the max scrollHeight
while d.execute_script("return window.pageYOffset") < 3000:
d.execute_script("window.scrollByPages(1)")
scrolled_pages = 1
sleep(0.2)
for my_elem in WebDriverWait(d, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//yt-formatted-string[@class='style-scope ytd-video-renderer' and @aria-label]"))):
tit.append(my_elem.text)
uj5u.com熱心網友回復:
要使用Python和Selenium在Youtube 上檢索視頻發布的日期/時間,您可以使用以下定位器策略:
代碼塊:
driver.get("https://www.youtube.com/results?search_query=' term '&sp=CAISAhAB") print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@id='metadata-line' and @class='style-scope ytd-video-meta-block']////following::span[2][contains(., 'hours') or contains(., 'day')]")))])控制臺輸出:
['2 hours ago', '2 hours ago', '3 hours ago', 'Streamed 3 hours ago', 'Streamed 3 hours ago', '5 hours ago', 'Streamed 6 hours ago', '6 hours ago', '6 hours ago', '7 hours ago', '8 hours ago', 'Streamed 8 hours ago', '9 hours ago', 'Streamed 10 hours ago', '11 hours ago']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402954.html
標籤:
