来自具有代码的页面(可以在检查元素中看到,而不是在源代码中看到)为:
<div id="download_div" class="row" style="margin-left: 2%; margin-right: 2%">
<p id="download_sub_text" class="hide-on-small-only" style="text-align: center;">
You could also download directly by
<a onclick="ga('send', 'event', 'link', 'click_here', 'wholesale.item');"
href="http://example.com/f2c9bd13afd7a17af35ad30a2c593c7f4bea2dd347b4149">
clicking here!
</a>
我想提取href链接。但是 driver.page_source
不起作用,因为它是脚本的一部分,因此如果不是源代码,我需要从哪里准确提取以及 xpath 这里?
另外,如果可能的话-此页面会触发文件下载(下载链接是-“http://example.com/f2c9bd13afd7a17af35ad30a2c593c7f4bea2dd347b4149”),因此如果可以捕获此链接,那么这将解决我的问题。
最佳答案
首先,要找到链接元素,请使用此 xpath -
//p[@id = 'download_sub_text']/a
然后,要获取属性的值,请使用 get_attribute()
方法。获取元素的 href
属性的值 -
required_url = driver.find_element_by_xpath("//p[@id = 'download_sub_text']/a").get_attribute("href")
print(required_url)
此外,如果您想获取点击后重定向到的链接,可以在点击按钮后获取current_url
-
required_button = driver.find_element_by_xpath("//p[@id = 'download_sub_text']/a")
required_button.click()
required_url = driver.current_url
关于javascript - 如何使用selenium从onclick javascript中提取url : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51604230/