Python Selenium驱动程序.get()在for循环中不工作

bttbmeg0  于 2022-11-24  发布在  Python
关注(0)|答案(2)|浏览(163)

下面的代码登录到一个YouTube帐户,一旦登录,它应该会访问一些YouTube视频。
问题在于:

  • 如果我做一个简单的直接链接,就像这里,它的工作

driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ')

  • 如果我循环访问多个链接,我会得到一个错误:

raise exception_class(message, screen, stacktrace)
InvalidArgumentException: invalid type: sequence, expected a string at line 1 column 8
完整代码如下

import time
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

def youtube_login():
    
    email = 'email@email.com'
    password = 'emailPassword'
    
        # Browser
    driver = webdriver.Firefox()
    driver.get('https://accounts.google.com/ServiceLogin?hl=en&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dsign_in_button%26app%3Ddesktop%26action_handle_signin%3Dtrue%26next%3D%252F&uilel=3&passive=true&service=youtube#identifier')
    
        # log in
    driver.find_element_by_id('identifierId').send_keys(email)
    driver.find_element_by_class_name('CwaK9').click()
    WebDriverWait(driver, 500).until(EC.element_to_be_clickable((By.NAME, "password")))
    driver.find_element_by_name('password').send_keys(password)
    driver.find_element_by_class_name('CwaK9').click()
    WebDriverWait(driver, 500).until(EC.element_to_be_clickable((By.ID, "identity-prompt-confirm-button")))
    driver.find_element_by_id('identity-prompt-confirm-button').click()
    
    #driver.get('https://www.youtube.com/watch?v=FFDDN1C1MEQ')  # If I do a simple direct link like here, it works
    
    urls = []
        
    # You can add in a file and import from there
    
    inp = open ("urls.txt","r")
    for line in inp.readlines():
        urls.append(line.split())
    
    for url in urls:        
        driver.get(url)
    
youtube_login()
h22fl7wq

h22fl7wq1#

我认为urls.txt中的URL格式不正确
尝试调试如下URL:

from selenium.common.exceptions import InvalidArgumentException

for url in urls:
    try:        
       driver.get(url)
    except InvalidArgumentException:
       print(url)
r3i60tvu

r3i60tvu2#

我在driver.get()之前用导入时间time.sleep(0.5)解决了这个问题。

相关问题