使用BeautifulSoup的默认HTML解析器,可以轻松地处理这种情况。只需将HTML字符串传递给BeautifulSoup构造函数并指定解析器类型(如果需要)即可。
例如:
from bs4 import BeautifulSoup
html = 'Cell 1 Cell 2 Cell 3 Cell 4
'
soup = BeautifulSoup(html, 'html.parser')
table = soup.find('table')
rows = table.find_all('tr')
for row in rows:
cells = row.find_all('td')
for cell in cells:
print(cell.text)
输出:
Cell 1
Cell 2
Cell 3
Cell 4
注意,第二个行(包含“Cell 3”)缺少一个完整的标记,但是使用BeautifulSoup时不会出现问题。