【问题标题】:How to extract url from onclick javascript using selenium : Python如何使用 selenium 从 onclick javascript 中提取 url:Python
【发布时间】:2018-07-31 01:19:12
【问题描述】:

来自具有代码的页面(可以在检查元素中看到,而不是在源代码中):

<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”)所以如果这个链接可以被捕获,那么这将解决我的问题。

【问题讨论】:

  • 你能提供实际的网址吗?

标签: javascript python selenium web-scraping


【解决方案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

【讨论】:

  • 不点击就可以提出解决方案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多