在python中使用漂亮的Soup解析html

2024-10-02 22:35:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下html:

<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<body>
<title>CATe - hj1612</title>
</td></tr></table>
</td></tr></table></td><td><img src="icons/arrowredright.gif"/></td><td align="center">
<input name="keyt" type="hidden" value="a3dvl"/>
<input type="submit" value="View"/><br/>or<br/>
<input type="reset" value="Reset"/>
</td>
</tr>
</body>
</html>

我试图得到keyt的值。既然是html,我使用的是BeautifulSoup。在

^{pr2}$

我知道你可以把soup.findid一起使用,就像soup.find(id="randomid")

但是soup.find(name="keyt")将不起作用,因为它不是主体标记。。。因此,我认为我应该使用普通的if substring in string:方法

for line in soup.find_all('input'):
    if "keyt" in line:
        print line

但是这个方法似乎不起作用,我对python还不熟悉,所以如果您能帮我/指出正确的方向,我将不胜感激


Tags: inlanginputvaluehtmltypelinebody
2条回答

你有一些奇怪的HTML。HEAD标签未关闭,td,table未打开。我甚至无法想象,汤怎么能解析它。在

from bs4 import BeautifulSoup

html = """
<html lang="en-US" xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>CATe - hj1612</title>
</td></tr></table>
</td></tr></table></td><td><img src="icons/arrowredright.gif"/></td><td align="center">
<input name="keyt" type="hidden" value="a3dvl"/>
<input type="submit" value="View"/><br/>or<br/>
<input type="reset" value="Reset"/>
</td>
</tr>
</html>
"""

soup = BeautifulSoup(html)

print soup.find(name="input", attrs={'name': 'keyt'})

输出:

^{pr2}$

如果要查找多个匹配项,可以使用find_all函数而不是find。至于如何使用这两个函数,name是您要查找的标记的名称,attrsdict是您真正用来查找具有特定属性的东西的东西,在您的例子中,name属性。在

相关问题 更多 >