Глобальный:
import re
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from patterns import PATTERNS
PATTERNS = {
'select_list': {
'click': r'javascript.*[0-9]+.*\s.*[0-9]+.*\s.*{}.*;',
'select_list_views': r'/Integration/chooselist/{}'
},
login: {"..."}
}
driver = webdriver.Firefox()
driver.get(r"login_uri")
Этот раздел направлен на целевую страницу,
views(PATTERNS['login']) # func performs login
list_name = r'ABC TEXT.COM'
pk = 1234
# get lists_views
lists_href = r'//a[@href="{}"]'.format(PATTERNS['select_list']['select_list_views'].format(pk))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, lists_href))).click()
source = driver.page_source # page source HTML
тогда element_href
нужно проанализировать с: source = driver.page_source
, используя флаг list_name
element_href = '//a[@href="{}".format(re.findall(r'javascript.*[0-9]+.*\s.*[0-9]+.*\s.*{}.*;'.format(list_name), source)[0])
будет любить:
'//a[@href="javascript:postSelect("123", "1234", "ABC TEXT.COM");"]'
который немного отличается от проверенного, кажется, что функция JS переформатирует ссылку, я не знаю, когда именно.
ссылка элемента из проверки:
<a href="javascript:postSelect("123", "1234", "ABC TEXT.com");">Select</a>
наконец, когда я пытаюсь выбрать элемент по XPATH:
try:
element_href = r'//a[@href="{}"]'.format(re.findall(PATTERNS['select_list']['click'].format(list_name), source)[0])
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
except IndexError:
print("could not parse link")
я смог щелкнуть элемент, выбрав его с копией XPATH из Firefox:
driver.find_element(By.XPATH, '/html/body/div[2]/div/div[4]/table/tbody/tr[104]/td[3]/a').click()
Единственная проблема с скопированным XPATH, нет динамического c способа сопоставить его с list_name
, так как 104 != 123
скрипты в html_source:
<div style="float: none; clear: both;"></div>
</div>
<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script><script src="https://some_url/jquery-ui-1.10.3.custom.min.js"></script>
<script src="https://some_url/jquery.ui.touch-punch.min.js"></script>
<script src="https://some_url/js/bootstrap.min.js"></script>
<script src="https://some_url/bootstrap-select.js"></script>
<script src="https://some_url/bootstrap-switch.js"></script>
<script src="https://some_url/flatui-checkbox.js"></script>
<script src="https://some_url/flatui-radio.js"></script>
<script src="https://some_url/jquery.tagsinput.js"></script>
<script src="https://some_url/jquery.placeholder.js"></script>
<script src="https://some_url/jquery.fancybox.min.js"></script>
<script type="text/javascript">
function ShowLoadingAJAX() {
$('body').addClass("loading");
}
function HideLoadingAJAX() {
$('body').removeClass("loading");
}
function DisplaySuccessMessage(msg) {
$('#alert_danger').hide();
$('#alert_info').hide();
$('#alert_success_message').html(msg);
$('#alert_success').show();
}
function AppendSuccessMessage(msg) {
$('#alert_danger').hide();
$('#alert_info').hide();
$('#alert_success_message').html($('#alert_success_message').html() + '<br/> → ' + msg);
$('#alert_success').show();
}
function DisplayErrorMessage(msg) {
$('#alert_success').hide();
$('#alert_info').hide();
$('#alert_danger_message').html(msg);
$('#alert_danger').show();
}
function DisplayInfoMessage(msg) {
$('#alert_danger').hide();
$('#alert_success').hide();
$('#alert_info_message').html(msg);
$('#alert_info').show();
}
function HideSuccessMessage() {
$('#alert_success_message').html('');
$('#alert_success').hide();
}
function HideErrorMessage() {
$('#alert_danger_message').html('');
$('#alert_danger').hide();
}
function HideInfoMessage() {
$('#alert_info_message').html('');
$('#alert_info').hide();
}
function loginAsSuperUser(id) {
$('#SuperLoginAsUserID').val(id);
$('#superLoginForm').submit();
}
$(document).ready(function () {
$('#some_string_body').css('display', 'block');
var tooltipOptions = { placement: 'right' };
$('.some_string_tooltip').tooltip(tooltipOptions);
var popoverOptions = { placement: 'right' };
$('.some_string_popover').popover(popoverOptions);
$('#alert_success_close_button').click(function (e) {
e.preventDefault();
$('#alert_success_message').html('');
$('#alert_success').hide();
});
$('#alert_danger_close_button').click(function (e) {
e.preventDefault();
$('#alert_danger_message').html('');
$('#alert_danger').hide();
});
$('#alert_info_close_button').click(function (e) {
e.preventDefault();
$('#alert_info_message').html('');
$('#alert_info').hide();
});
});
</script>
<script>
var href_parts = window.location.href.split('/');
var lastFancyboxHeight = 0;
var fancyDocReady = false;
var fancyRefreshParent = false;
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function getFancyboxY(id) {
var bs = $('#' + id + '-box-statement');
if (bs.length && bs.offset() && bs.offset().top) {
return (bs.offset().top + 'px');
} else {
return '200px';
}
}
function showActivityLog() {
var href_iframe_url = href_parts[0] + '//' + href_parts[2] + '/Activity/Recent';
//$('#fancy-styler').html('.fancy-styler-top { top: ' + getFancyboxY(id) + ' !important; }');
$.fancybox({
type: 'iframe',
href: href_iframe_url,
scrolling: 'no',
padding: 0,
openEffect: 'none',
closeEffect: 'none',
closeClick: false,
nextClick: false,
autoResize: false,
autoHeight: false,
autoSize: false,
autoCenter: true,
fitToView: false,
//fixed: false,
width: 1160,
height: 900,
tpl: {
closeBtn: '<div style="position: absolute; top: -22px; left: 0px; z-index: 8040; height: 28px; line-height: 30px; background-color: #428bca; color: #fff; cursor: pointer; font-size: 14px; font-weight: bold; padding-left: 12px; padding-right: 12px; border-top-right-radius: 6px; border-top-left-radius: 6px;">Recent Activity</div>'
},
afterClose: function () {
},
beforeShow: function () {
//$(".fancybox-wrap").addClass("fancy-condition-editor-2");
$(".fancybox-wrap").addClass("fancy-styler-top-2");
}
});
}
function getActivitiesColorAjax() {
NumProfileActivityChecks++;
if ($('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').length) {
$.ajaxSetup({ cache: false });
var dataPost = {
__RequestVerificationToken: $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
p1: "a",
p2: "b"
};
$.post("/Activity/PostColorAjax", dataPost, function (data) {
if (!data.color || data.color === 'green') {
//$('#profile-name-icon').css('color', '#1abc9c');
$('#profile-name-icon').css('color', OriginalProfileNameIconColor);
} else {
$('#profile-name-icon').css('color', '#e74c3c');
}
//console.log('PostColorAjax (' + NumProfileActivityChecks + '): ' + data.color);
if (NumProfileActivityChecks <= 10) {
//for the first 10 minutes, check every 60 seconds.
setTimeout(getActivitiesColorAjax, 60000);
} else if (NumProfileActivityChecks <= 120) {
//for the first 120 minutes, check every 120 seconds.
setTimeout(getActivitiesColorAjax, 120000);
} else {
//after 120 minutes, start checking with exponential backoff.
//120 + (NumProfileActivityChecks - 120) * 2
var tot = 1000 * (120 + Math.pow((NumProfileActivityChecks - 120), 2));
setTimeout(getActivitiesColorAjax, tot);
}
});
}
}
</script>
<script type="text/javascript">
$(document).ready(
function () {
//$('a[rel="popover"]').popover({placement: 'bottom'});
//$('#settings_general_mc_api_key_error').addClass('alert-error error');
}
);
function postSelect(id, connectionID, ListName)
{
$("#ID").val(id.toString());
$("#IntegrationID").val(connectionID);
$("#ListName").val(ListName);
$("#emChooseListForm").submit();
}
</script>
</body>
</html>
Хотя ссылка сопоставляется непосредственно с исходным кодом страницы, драйвер не может найти элемент и просто время ожидания.
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
Traceback (most recent call last):
File "<ipython-input-53-7a3495af695d>", line 1, in <module>
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, element_href))).click()
File "c:\python\python37\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
TimeoutException
Пожалуйста, терпите мое описание, если оно плохое, это мой первый пост на stackoverflow, спасибо