在python/bs4之前获取文本

2024-05-23 14:02:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从一个网页上获取一些数据。标记文本中有换行符和<br/>标记。我只想知道标签开头的电话号码。你能给我一个建议,怎样才能只得到号码吗?在

以下是HTML代码:

<td>
    +421 48/471 78 14



    <br />
    <em>(bowling)</em>
</td>

beautifulsoup中有没有一种方法可以在标记中获取文本,但只获取不被其他标记包围的文本?第二件事:去掉文本换行符和html换行符?在

我用BS4。在

输出将是:“+421484717814”

你有什么想法吗? 谢谢你


Tags: 数据代码标记文本br网页html电话号码
2条回答
html="""
<td>
    +421 48/471 78 14



    <br />
    <em>(bowling)</em>
</td>
"""


from bs4 import BeautifulSoup

soup = BeautifulSoup(html)

print soup.find("td").contents[0].strip() 
+421 48/471 78 14

print soup.find("td").next_element.strip()
+421 48/471 78 14

soup.find("td").contents[0].strip()找到tag的内容,我们得到了它的第一个元素,并用str.strip()删除所有{}换行符。在

从文档next_element

字符串或标记的.next_element属性指向随后立即解析的内容

对你有用吗?在

>>> from bs4 import BeautifulSoup
>>> str = str.replace("\n", "") # get rid of newlines
>>> str = "<td>   +421 48/471 78 14    <br /><em>(bowling)</em></td>"
>>> for item in soup.td.children:
...   phone = item # first item is the phone number
...   break
... 
>>> phone
u'   +421 48/471 78 14    '
>>> phone.strip()
u'+421 48/471 78 14'
>>> 

相关问题 更多 >