我们是否可以编写python自动化代码,每次打开不同的url,修改以前的url?

2024-04-20 13:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

2条回答

提供的示例是用Java编写的,但用Python编写不会有问题

首先,您至少需要将URL存储在列表或数组中。 然后由JS executor打开选项卡并循环:

String[] relativeUrls = {"url_1", "url_2", "url_3"};
JavascriptExecutor jse = (JavascriptExecutor) driver; // this is your driver object


ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());

for (int i = 0; i < relativeUrls.size(); i++) {
  jse.executeScript("window.open()");
  driver.switchTo().window(tabs.get(1));
  driver.navigate().to(driver.getCurrentUrl() + relativeUrls[i]);
  driver.close();
}

将所有链接存储在下面这样的列表中,然后有一个loop并在其中使用driver.get()打开一个链接,您需要确保的是,保留current window handle(对于每个窗口都是唯一的),然后switch to

您可以这样做:

links = ["https://australiapopulation.com/lucifer-season-1-subtitles/", "https://australiapopulation.com/lucifer-season-2-subtitles/", "https://australiapopulation.com/lucifer-season-3-subtitles/"]
number_of_tabs = len(links)
count = 1
for link in links :
  driver.get(link)
  windows_before = driver.current_window_handle
  driver.execute_script("window.open('');")
  #WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(number_of_tabs))
  new_window = driver.window_handles[count]
  count = count + 1
  driver.switch_to.window(new_window)
  sleep(3)

相关问题 更多 >