使用urllib和beautifulsoup查找“隐藏”标签中的值
我想知道是否可以显示隐藏标签的值。我正在使用urllib和beautifulsoup,但似乎无法得到我想要的结果。
我使用的HTML代码如下:(保存为hiddentry.html)
<html>
<head>
<script type="text/javascript">
//change hidden elem value
function changeValue()
{
document.getElementById('hiddenElem').value = 'hello matey!';
}
//this will verify if i have successfully changed the hiddenElem's value
function printHidden()
{
document.getElementById('displayHere').innerHTML = document.getElementById('hiddenElem').value;
}
</script>
</head>
<body>
<div id="hiddenDiv" style="position: absolute; left: -1500px">
<!--i want to find the value of this element right here-->
<span id="hiddenElem"></span>
</div>
<span id="displayHere"></span>
<script type="text/javascript">
changeValue();
printHidden();
</script>
</body>
</html>
我想打印的是ID为hiddenElem的元素的值。为此,我尝试使用urllib和beautifulsoup的组合。我的代码是:
from BeautifulSoup import BeautifulSoup
import urllib2
import urllib
mysite = urllib.urlopen("http://localhost/hiddentry.html")
soup = BeautifulSoup(mysite)
print soup.prettify()
print '\n\n'
areUthere = soup.find(id="hiddenElem").find(text=True)
print areUthere
不过,我得到的输出是None。有没有什么想法?我想做的事情真的可能吗?
1 个回答
2
BeautifulSoup 是一个用来解析从服务器获取的 HTML 的工具。如果你想看到生成的值,你需要在把字符串传给 BeautifulSoup 之前,先执行页面上嵌入的 JavaScript。也就是说,先运行 JavaScript,然后把修改过的 DOM HTML 传给 BeautifulSoup。
关于浏览器模拟:
- 这个来自 jQuery 创始人的组合看起来很有趣
- SO 问题 把浏览器带到服务器
- 还有 SO 问题 无头浏览器
通过使用浏览器模拟,你应该能够下载基础的 HTML,运行浏览器模拟来执行 JavaScript,然后把修改过的 DOM HTML 传给 BeautifulSoup。