我正在尝试编写一个转到youtube频道的python脚本。单击“视频”选项卡。然后在网页上搜索内容。我很好地抓取内容,直到...我得到了更多的加载按钮。 python脚本我设法点击加载更多按钮一次,但它再也没有按下它:'(我怎么能修改代码我必须让它一次又一次地点击它直到它不存在。那样,我可以打开用户的完整频道并从他们拥有的每个视频中获取信息。谢谢你。
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
^^这些是我导入的模块。我不知道如何将NoSuchElementException添加到我的代码中。这是代码:
chrome_path = r"/Users/jack/Desktop/Other/Downloads/Software_and_Programs/chromedriver"
browser = webdriver.Chrome(chrome_path)
YOUTUBER_HOME_PAGE_URL = "https://www.youtube.com/user/Google/videos"
PATIENCE_TIME = 60
LOAD_MORE_BUTTON_XPATH = '//*[@id="browse-itemsprimary"]/li[2]/button/span/span[2]'
def waitForLoad(inputXPath):
Wait = WebDriverWait(browser, PATIENCE_TIME)
Wait.until(EC.presence_of_element_located((By.XPATH, inputXPath)))
loadMoreButtonExists = True
while loadMoreButtonExists:
try:
waitForLoad(LOAD_MORE_BUTTON_XPATH)
WebDriverWait(browser, PATIENCE_TIME)
loadMoreButton = browser.find_element_by_partial_link_text('Load More')
#loadMoreButton = browser.find_element_by_xpath(LOAD_MORE_BUTTON_XPATH)
loadMoreButton.click()
except:
print 'we have completely loaded every video from this Youtuber. Now we will scrape the video content\n'
loadMoreButtonExists = False
我使用了xpath方式,但似乎仍无法正常工作。我已在上面的代码中注释掉了。如果我能得到这方面的帮助,那真是太棒了。我找不到任何好的答案。我相信它可以用硒来完成,但如果没有,我应该使用什么?
答案 0 :(得分:4)
您可以使用以下代码进行滚动
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
#browser = webdriver.Firefox()#Chrome('./chromedriver.exe')
YOUTUBER_HOME_PAGE_URL = "https://www.youtube.com/user/Google/videos"
PATIENCE_TIME = 60
LOAD_MORE_BUTTON_XPATH = '//*[@id="browse-itemsprimary"]/li[2]/button/span/span[2]'
driver = webdriver.Chrome('./chromedriver.exe')
driver.get(YOUTUBER_HOME_PAGE_URL)
while True:
try:
loadMoreButton = driver.find_element_by_xpath("//button[contains(@aria-label,'Load more')]")
time.sleep(2)
loadMoreButton.click()
time.sleep(5)
except Exception as e:
print e
break
print "Complete"
time.sleep(10)
driver.quit()