python - 无法通过 XPATH 选择元素
问题描述
全球的:
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
thenelement_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")
我可以通过使用从 Firefox 复制的 XPATH 选择它来单击该元素:
driver.find_element(By.XPATH, '/html/body/div[2]/div/div[4]/table/tbody/tr[104]/td[3]/a').click()
复制的 XPATH 的唯一问题是,没有动态方式将其映射到,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上的第一篇文章,谢谢
解决方案
推荐阅读
- javascript - 当服务器从不停止加载时,如何在 JavaScript 中存储来自 get 请求的初始文本/事件流响应?
- docker - 如何检查 trivy 是否启动并运行
- r - 如何调整 read_excel 使千位分隔符不更改为小数点?
- angular - 如何访问由调用组件以角度绑定的对象的属性?
- r - R - Gamma 分布 - 线性混合效应模型 - lmer/glmer 错误
- html - 如何处理 RenderHtml 组件中的溢出
- javascript - 如何使用“signup.js”之类的外部脚本检查两个字段的身份?
- opencv - 如何使用 OpenCV 进行 OCR 和文本检测识别
- database - 什么时候在应用程序中初始化数据库连接
- excel - PowerShell 中的 Excel - 我真的有一个有效的会话吗?