【发布时间】:2012-09-05 13:48:45
【问题描述】:
我正在学习python和beautifulsoup,在网上看到了这段代码:
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
html = ['<html><body><p align="center"><b><font size="2">Table 1</font></b><table><tr><td>1. row 1, cell 1</td><td>1. row 1, cell 2</td></tr><tr><td>1. row 2, cell 1</td><td>1. row 2, cell 2</td></tr></table><p align="center"><b><font size="2">Table 2</font></b><table><tr><td>2. row 1, cell 1</td><td>2. row 1, cell 2</td></tr><tr><td>2. row 2, cell 1</td><td>2. row 2, cell 2</td></tr></table></html>']
soup = BeautifulSoup(''.join(html))
searchtext = re.compile(r'Table\s+1',re.IGNORECASE)
foundtext = soup.find('p',text=searchtext) # Find the first <p> tag with the search text
table = foundtext.findNext('table') # Find the first <table> tag that follows it
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
try:
text = ''.join(td.find(text=True))
except Exception:
text = ""
print text+"|",
print
虽然其他一切都很清楚,但我无法理解连接是如何工作的。
text = ''.join(td.find(text=True))
我尝试在 BS 文档中搜索 join,但我找不到任何东西,也无法真正在线找到有关如何在 BS 中使用 join 的帮助。
请告诉我这条线是如何工作的。谢谢!
PS:上面的代码来自另一个stackoverflow页面,它不是我的作业:) How can I find a table after a text string using BeautifulSoup in Python?
【问题讨论】:
标签: python beautifulsoup