我试图在一个窗口中的新选项卡中打开URL列表,但改为在新窗口中打开它们。请帮忙。这是我的URL.csv
SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com
import csv
from selenium import webdriver
def csv_url_reader(url_obj):
reader = csv.DictReader(url_obj, delimiter=',')
for line in reader:
url = line["URL"]
title = line["Title"]
print(url + title)
driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
driver.get(url)
if __name__ == "__main__":
with open("URL.csv") as url_obj:
csv_url_reader(url_obj)
答案 0 :(得分:1)
在您发布的代码段中,您是在驱动程序实例中打开URL,而不是在新选项卡中打开。
相反,您应该尝试像这样打开新标签页:
import csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
def csv_url_reader(url_obj):
reader = csv.DictReader(url_obj, delimiter=',')
for line in reader:
url = line["URL"]
title = line["Title"]
print(url + title)
driver.execute_script("window.open(" + url + ",'_blank');")
if __name__ == "__main__":
with open("URL.csv") as url_obj:
csv_url_reader(url_obj)
答案 1 :(得分:0)
将driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
放入循环中时,您将为每个网站创建一个新的webdriver实例。
尝试这样的事情:
import csv
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def csv_url_reader(url_obj):
reader = csv.DictReader(url_obj, delimiter=',')
driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
for line in reader:
url = line["URL"]
title = line["Title"]
print(url + title)
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.get(url)
if __name__ == "__main__":
with open("URL.csv") as url_obj:
csv_url_reader(url_obj)
time.sleep(9999999)
答案 2 :(得分:0)
要添加新标签,请使用
send_keys(Keys.COMMAND + 't')
对于Mac,
要么
send_keys(Keys.CTRL + 't')
用于Windows