У меня есть список путей, как я могу открыть каждый из них на отдельной вкладке? - PullRequest
0 голосов
/ 21 апреля 2019

По сути, у меня есть веб-сайт, на котором мне нужно открыть несколько вкладок и что-то сделать в каждой из них. Как я могу сделать это, используя Python + Selenium и Chrome? Вот код, который у меня есть:

from selenium import webdriver
import os
import time
import pyautogui
option = webdriver.ChromeOptions()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
chrome_prefs["profile.default_content_settings"] = { "popups": 2 }
option.add_argument("--disable-notifications")


    driver = webdriver.Chrome(chrome_options=option)
    driver.get('https://www.spiritfanfiction.com/login')
    driver.find_element_by_xpath("//*[@id='Usuario']").send_keys("breakfast")
    driver.find_element_by_xpath("//*[@title='Senha']").send_keys("302290679")
    driver.find_element_by_xpath("//*[@class='btn btn-primary']").send_keys("302290679")
    driver.find_element_by_xpath("//*[@class='btn btn-primary']").click()

#this opens the page I need to get all the xpaths from 
    LinkDoPerfil = driver.get("https://www.spiritfanfiction.com/recentes?pagina=1000")

#this is the xpath I need to open in each tab
    transactionElements = driver.find_elements_by_xpath("//*[@class='usuario usuarioPopupTrigger link']")

#this is the part I have no idea what I'm doing lol. But it was supposed to open all the xpaths in a different tab.      
    for element in transactionElements:
            ActionChains(driver) \
                .key_down(Keys.CONTROL) \
                .click(element) \
                .key_up(Keys.CONTROL) \
                .perform()

#this switches to the latest opened tab, which is the final xpath I got from the page.
    driver.switch_to_window(driver.window_handles[-1])
    try:
            driver.find_element_by_xpath('//*[@class="fa fa-eye"]').click()
    except:
            browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

Может кто-нибудь сказать мне, что не так? Раньше это работало, но я все испортил, а теперь нет. Ничего не происходит после:

LinkDoPerfil = driver.get("https://www.spiritfanfiction.com/recentes?pagina=1000")

1 Ответ

0 голосов
/ 21 апреля 2019

Я вижу, что вы не импортировали некоторые классы, а также я внес некоторые изменения в ваш код.

#import libraries
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import os
import time

# set options for web driver
option = webdriver.ChromeOptions()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
chrome_prefs["profile.default_content_settings"] = { "popups": 2 }
option.add_argument("--disable-notifications")

driver = webdriver.Chrome(chrome_options=option)
driver.get('https://www.spiritfanfiction.com/login')

driver.find_element_by_xpath("//*[@id='Usuario']").send_keys("breakfast")
driver.find_element_by_xpath("//*[@title='Senha']").send_keys("302290679")
driver.find_element_by_xpath("//*[@class='btn btn-primary']").send_keys("302290679")
driver.find_element_by_xpath("//*[@class='btn btn-primary']").click()

LinkDoPerfil = driver.get("https://www.spiritfanfiction.com/recentes?pagina=1000")
transactionElements = driver.find_elements_by_xpath("//*[@class='usuario usuarioPopupTrigger link']")
for element in transactionElements:
            ActionChains(driver) \
                .key_down(Keys.CONTROL) \
                .click(element) \
                .key_up(Keys.CONTROL) \
                .perform()

# Store all the tabs in the variable
tabs = driver.window_handles
# Switch to each tab opened one by one
for x in tabs[1:]:
    time.sleep(2)
    driver.switch_to_window(x)
    '''
    Do whatever you want in each tab here
    '''

внутри цикла for перейдите на каждую вкладку и сделайте то, что вы хотите, добавьте нужный коддрайвер для выполнения.Пожалуйста, прокомментируйте, если у вас есть проблемы с пониманием какой-либо части кода.

...