具有以下代码的页面(可以在inspect元素中看到,而不是在源代码中看到):
<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”),因此,如果可以捕获此链接,则可以解决我的情况。
答案 0 :(得分:1)
首先,要使用以下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