使用BeautifulSoup从html表中获取数据

时间:2014-02-21 17:56:12

标签: python-2.7 beautifulsoup

我很难从html表中提取数据。我有以下python代码,但它给我一个错误消息:

  

文件" request_test.py",第50行       print(soup.find_all(" td",class =" station tqdetail top"))                                     ^ SyntaxError:语法无效

from bs4 import BeautifulSoup

html_doc = """
<html>
<body>

<table>
<tr>
<th colspan="2">an</th>
<th>Halt</th>
<tr>
<td class="arrival tqdetail">
17:24
<br />
17:24
</td>
<td class="tqdetail rt top">
<span class="okmsg bold">+0</span>
<br />
<span class="okmsg bold">+0</span>
</td>
<td class="station tqdetail top">
Foo
<br />
</td>
</tr>

</body>
</html>
"""

soup = BeautifulSoup(html_doc)

print(soup.find_all("td", class="station tqdetail top"))

我不知道我在这里做错了什么,我很欣赏这里的任何线索。

2 个答案:

答案 0 :(得分:0)

class是python中的保留字。该函数应为soup.find_all("td", class_="station tqdetail top")(在课后注意下划线)。有关详细信息,请参阅http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class

答案 1 :(得分:0)

此处您可以class使用soup

print(soup.find_all("td", {"class":"station tqdetail top"}))