我正试图从几个网页中提取数据,这些网页在显示表格的方式上并不一致。我需要编写代码来搜索文本字符串,然后立即转到该特定文本字符串后面的表。然后我要提取那个表的内容。到目前为止我得到的是:
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('Table 1',re.IGNORECASE) # Also need to figure out how to ignore space
foundtext = soup.findAll('p',text=searchtext)
soupafter = foundtext.findAllNext()
table = soupafter.find('table') # find the next table after the search string is found
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
但是,我得到以下错误:
soupafter = foundtext.findAllNext()
AttributeError: 'ResultSet' object has no attribute 'findAllNext'
有没有一个简单的方法来做到这一点使用美化组?
错误是由于^{} 是} 可能就足够了,它只返回第一个匹配的标记。
Tag
对象的方法,而foundtext
是ResultSet
对象,是匹配标记或字符串的列表所致。您可以遍历foundtext
中的每个标记,但根据需要,使用^{这是你的代码的修改版本。在将
foundtext
改为使用soup.find
之后,我发现并修复了table
的相同问题。我把你的正则表达式修改为ignore whitespace between the words:这将输出:
相关问题 更多 >
编程相关推荐