This issue has been bothering me for several days, and I have not been able to find a suitable solution. Currently, I am using Python and Selenium for web scraping. After clicking a button on the first website, it forces the opening of a second website, which triggers an alert popup. However, despite trying many methods, I have been unable to capture the alert popup to proceed with the subsequent automated operations. If I use keyboard.press(Key.enter)
, other operations may interfere. I would like to know if anyone has encountered a similar situation and can provide a solution. The simulated situation of the website is as shown in the HTML below. Thank you very much.
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>upload picture</title>
</head>
<body>
<button id="openWindow">Open new window</button>
<div>
<h3>Uploaded images will appear below:</h3>
<img id="uploadedImage1" src="" alt="uploadedImage1" style="max-width: 500px;">
<img id="uploadedImage2" src="" alt="uploadedImage2" style="max-width: 500px;">
</div>
<script>
let uploadCount = 0;
document.getElementById('openWindow').onclick = function() {
const newWindow = window.open('upload.html', 'Upload Image', 'width=500,height=500');
newWindow.focus();
};
window.addEventListener('message', function(event) {
if (event.origin !== window.location.origin) {
alert('Data from unknown sources!');
return;
}
uploadCount++;
const imageURL = event.data;
if (uploadCount === 1) {
document.getElementById('uploadedImage1').src = imageURL;
} else if (uploadCount === 2) {
document.getElementById('uploadedImage2').src = imageURL;
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>upload picture2</title>
<script>
window.onload = function() {
alert('Please select a picture and upload it!');
};
</script>
</head>
<body>
<input type="file" id="fileInput">
<button id="uploadButton">upload</button>
<script>
document.getElementById('uploadButton').onclick = function() {
const fileInput = document.getElementById('fileInput');
if (fileInput.files.length === 0) {
alert('Please select a profile!');
return;
}
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function(e) {
window.opener.postMessage(e.target.result, window.opener.location.origin);
window.close();
};
reader.readAsDataURL(file);
};
</script>
</body>
</html>
Aside from the methods in the official documentation,
refresh the page after entering the second website to recapture the current window, increase the waiting time to capture the popup content, and switch back to the main execution window…
So far, none of these methods can capture the new window and alert popup. If I manually interact with the alert during the automation process, only then can I capture the new browser page.
user25117354 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.