我发现很难使用 python 2.7 和 selenium <获取HTML页面的<!-- stuff -->
标记中包含的HTML评论标记head
的内容/强>
<head>
<!-- I would like to get this sentence -->
[...]
</head>
我使用FirePath / FireBug得到了该评论的XPath(所以我假设它是正确的):html/head/comment()[1]
。
然后:
given_driver.find_element_by_xpath('html/head/comment()[1]')
给了我InvalidSelectorException
Message: The given selector html/head/comment()[1] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: The result of the xpath expression "html/head/comment()[1]" is: [object Comment]. It should be an element.
head_element = given_driver.find_element_by_xpath('html/head')
然后在head
标记中为head_element.get_attribute('innerHTML')
提供了完整的HTML代码,例如:u'<!-- I would like to get this sentence -->\n [...]
但我想在head
标记内只获取评论标记的内容。我想知道这对Selenium来说是不可能的,但对我来说这似乎很奇怪。我怎么能得到它?
答案 0 :(得分:2)
Selenium API不支持评论节点。但是你可以通过这段JavaScript轻松获得评论:
head = driver.find_element_by_css_selector("head")
comment = get_element_comment(head)
print(comment)
def get_element_comment(element):
return element._parent.execute_script("""
return Array.prototype.slice.call(arguments[0].childNodes)
.filter(function(e) { return e.nodeType === 8 })
.map(function(e) { return e.nodeValue.trim() })
.join('\n');
""", element)
答案 1 :(得分:0)
您必须获取页面源并从那里查找(解析)所需的注释。像这样:
driver.Navigate().GoToUrl("your url");
var src = driver.PageSource;
然后解析src