Stu*_*Cat 4 python beautifulsoup
假设我的html看起来像这样:
<td>Potato1 <span somestuff...>Potato2</span></td>
...
<td>Potato9 <span somestuff...>Potato10</span></td>
Run Code Online (Sandbox Code Playgroud)
我有美丽的做法:
for tag in soup.find_all("td"):
print tag.text
Run Code Online (Sandbox Code Playgroud)
我明白了
Potato1 Potato2
....
Potato9 Potato10
Run Code Online (Sandbox Code Playgroud)
是否可以只获取标签内的文本,而不是嵌套在span标签内的任何文本?
你可以使用.contentsas
>>> for tag in soup.find_all("td"):
... print tag.contents[0]
...
Potato1
Potato9
Run Code Online (Sandbox Code Playgroud)
它能做什么?
使用标签将标签作为列表提供.contents.
>>> for tag in soup.find_all("td"):
... print tag.contents
...
[u'Potato1 ', <span somestuff...="">Potato2</span>]
[u'Potato9 ', <span somestuff...="">Potato10</span>]
Run Code Online (Sandbox Code Playgroud)
因为我们只对第一个元素感兴趣,所以我们选择
print tag.contents[0]
Run Code Online (Sandbox Code Playgroud)