javascript - 如何使用 selenium 获取带有 javascript 呈现的源代码的 html

标签 javascript python selenium

我在一个网页中运行查询,然后得到结果 url。如果我右键查看 html 源代码,我可以看到 JS 生成的 html 代码。如果我只是使用 urllib,python 无法获取 JS 代码。所以我看到了一些使用 Selenium 的解决方案。这是我的代码:

from selenium import webdriver
url = 'http://www.archives.com/member/Default.aspx?_act=VitalSearchResult&lastName=Smith&state=UT&country=US&deathYear=2004&deathYearSpan=10&location=UT&activityID=9b79d578-b2a7-4665-9021-b104999cf031&RecordType=2'
driver = webdriver.PhantomJS(executable_path='C:\python27\scripts\phantomjs.exe')
driver.get(url)
print driver.page_source

>>> <html><head></head><body></body></html>         Obviously It's not right!!

这是我在右键窗口中需要的源代码,(我想要 INFORMATION 部分)

</script></div><div class="searchColRight"><div id="topActions" class="clearfix 
noPrint"><div id="breadcrumbs" class="left"><a title="Results Summary"
href="Default.aspx?    _act=VitalSearchR ...... <<INFORMATION I NEED>> ... 
to view the entire record.</p></div><script xmlns:msxsl="urn:schemas-microsoft-com:xslt">

        jQuery(document).ready(function() {
            jQuery(".ancestry-information-tooltip").actooltip({
href: "#AncestryInformationTooltip", orientation: "bottomleft"});
        });

所以我的问题是:如何获取JS生成的信息?

最佳答案

您需要通过 javascript 获取文档你可以使用 Selenium execute_script功能

from time import sleep # this should go at the top of the file

sleep(5)
html = driver.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
print html

这将得到 <html> 中的所有内容标记

关于javascript - 如何使用 selenium 获取带有 javascript 呈现的源代码的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22739514/

相关文章:

javascript - 从数据表中搜索

python - Pygame 不关闭

python - 无法使用 Python Paramiko 执行带有重定向多行输入的 shell 命令

python - 仅对数组中的单个值进行排序

javascript - 如何在 Protractor 中只运行失败的测试

javascript - 如何动态绑定(bind)ajax数据中的jquery静态数据

javascript - 如何将数据传递给正在重用的组件?

javascript - Jquery改变html标签

google-chrome - 与 mocha 一起使用时,WebDriverjs 未加载 url

java - 从webtable中获取值并循环写入excel表中的每一行