-1

我想在 Python 中访问一个由 JavaScript 处理的链接,如下所示:

<a href="#" class="example"> Hello World </a>

我想根据元素的class属性或id属性从 HTML 字符串中找到链接。<a>

是否有可能在 Python 中做到这一点?

4

1 回答 1

1

你不能,因为那是一个自引用链接。您已经打开了文档。

URL 中的A#表示文档中的位置。当 URL以 a开头时#,它是当前文档中的位置;浏览器将滚动到任何以#. 在以下示例中,单击<a href="#footer">链接指示浏览器滚动文档以将<div id="footer">元素定位在浏览器窗口的顶部:

<a href="#footer">to the end of the document</a>

<!-- long document follows -->

<div id="footer">Something at the bottom of the document</div>

当 URL包含 a#时,该 URL 是无操作的。它是一个占位符,用于 JavaScript 通常拦截链接点击。使用 Python 处理此文档时,您可以完全忽略它。您的 Python HTML 解析器不是浏览器,没有运行 JavaScript 来处理该链接元素上的鼠标点击。甚至没有鼠标点击。

如果您尝试处理 JavaScript 驱动的页面,您可以使用 JavaScript 调试器(大多数浏览器附带)来确定它在做什么,或者运行由 Python 控制的无头浏览器。你可以使用Ghost.py来做后者:

from ghost import Ghost
ghost = Ghost()
page, extra_resources = ghost.open("http://jeanphi.fr")
assert page.http_status==200 and 'jeanphix' in ghost.content

这运行一个无头 Webkit 浏览器。

于 2013-06-30T22:02:54.637 回答