[英]Parse table with BeautifulSoup Python
如果我要读取遵循以下格式的表中的条目:
<table cellspacing="0" cellpadding="4">
stuff
</table>
我将其用作当前方法:
pg = urllib2.urlopen(req).read()
page = BeautifulSoup(pg)
table = page.find('table', cellpadding = 4, cellspacing = 0)
我的table
无法正确读取标签,什么是最好的方法?
我已经在BeautifulSoup版本3和4中对此进行了测试。您的代码可与BS4一起使用,因此您必须使用版本3。
>>> from bs4 import BeautifulSoup as BS4 # Version 4
>>> from BeautifulSoup import BeautifulSoup as BS3 # Version 3
>>> bs3soup = BS3("""<table cellspacing="0" cellpadding="4">
...
... stuff
...
... </table>""")
>>> bs4soup = BS4("""<table cellspacing="0" cellpadding="4">
...
... stuff
...
... </table>""")
>>> bs3soup.find('table', cellpadding = 4, cellspacing = 0) # None
>>> bs4soup.find('table', cellpadding = 4, cellspacing = 0)
<table cellpadding="4" cellspacing="0">
stuff
</table>
因此,如果您想继续使用BS3,应该可以解决此问题:
>>> soup.find('table', cellpaddin="4", cellspacing="0") # Notice how the integers are now strings, like in the HTML.
但是,您应该使用版本4( from bs4 import BeautifulSoup
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.