我在一个网页中运行查询,然后得到结果 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/