如何在python中的html中获取文本

时间:2011-10-06 10:23:19

标签: python

我想用python捕获html中的一些文本。 例如..

#!/usr/bin/python
import urllib

open = urllib.urlopen('http://localhost/main.php')
read = open.read()
print read

和目标网址的源代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Untitled Document</title>
</head>

<body>
This is body!
</body>
</html>

如果我只想听到“这是身体!”只要!? 请伙计们,帮我解决这个问题!


例如,HTML被这一个取代:

<table width=90% align=center>
  <tr>
    <td>The information available on this site freely accessible to the public</td>
  <tr>
</table>
<table class=adminlist border=0 width=90% cellpadding=3 cellspacing=0 align=center>
  <tr>
    <td rowspan=5 colspan=2><img src=images/Forum.png><br></td>
  </tr>
  <tr>
    <td><i><b>Phone</b></td><td>: +61 2 4446 5552</td>
  </tr>
  <tr>
    <td><i><b>Name</b></td><td>: Stundet</td>
  </tr>
  <tr>
    <td><i><b>Class</b></td>
    <td>: Summer</td>
  </tr>
  <tr>
    <td><i><b>Email</b></td>
    <td>: student@localhost.com</td>
  </tr>
</table>

我想做这个输出:

Phone : +61 2 4446 5552
Name  : Student
Class : Summer
Email : student@localhost.com

只抓住了html核心的话......:)

2 个答案:

答案 0 :(得分:6)

尝试beautiful soup

from BeautifulSoup import BeautifulSoup

...

soup = BeautifulSoup(html)
soup.findAll("body").string

答案 1 :(得分:4)

使用BeautifulSoup

from BeautifulSoup import BeautifulSoup

html = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Untitled Document</title>
</head>

<body>
This is body!
</body>
</html>
"""
soup = BeautifulSoup(html)

print soup.find('body').string