繁体   English   中英

如何删除BeautifulSoup中的所有不同脚本标记?

[英]How can I remove all different script tags in BeautifulSoup?

我从Web链接爬行表,并希望通过删除所有脚本标记来重建表。 这是源代码。

response = requests.get(url)
soup = BeautifulSoup(response.text)
table = soup.find('table')

for row in table.find_all('tr') :                                                                                                                                                                                                                                                                                                                                                                                                     
    for col in row.find_all('td'):
        #remove all different script tags
        #col.replace_with('') 
        #col.decompose()  
        #col.extract()
        col = col.contents

如何删除所有不同的脚本标记? 以跟随单元格为例,其中包括标签abrtd

<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>

我的预期结果是:

Signal et Communication
Ingénierie Réseaux et Télécommunications

你问的是get_text()

如果只需要文档或标记的文本部分,则可以使用get_text()方法。 它返回文档中或标记下的所有文本,作为单个Unicode字符串

td = soup.find("td")
td.get_text()

请注意,在这种情况下, .string将返回None ,因为td 有多 .string

如果一个标签包含多个东西,那么不清楚.string应该引用什么,所以.string被定义为None

演示:

>>> from bs4 import BeautifulSoup
>>> 
>>> soup = BeautifulSoup(u"""
... <td><a href="http://www.irit.fr/SC">Signal et Communication</a>
... <br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
... </td>
... """)
>>> 
>>> td = soup.td
>>> print td.string
None
>>> print td.get_text()
Signal et Communication
Ingénierie Réseaux et Télécommunications

尝试调用col.string。 那只会给你文字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM