在Python/bs4中获取<br/>前的文本
我正在尝试从一个网页上抓取一些数据。这个标签的文本里有换行符和<br/>
标签。我只想获取标签开头的电话号码。你能给我一些建议,告诉我怎么只提取这个号码吗?
这是HTML代码:
<td>
+421 48/471 78 14
<br />
<em>(bowling)</em>
</td>
在beautifulsoup中,有没有办法只获取标签里的文本,而不包括其他标签包围的文本?还有,怎么去掉文本中的换行符和HTML中的换行符呢?
我使用的是BS4。
我想要的输出是:'+421 48/471 78 14'
你有什么想法吗?谢谢!
3 个回答
1
另一种方法是使用 decompose()
方法来去掉标签。这个方法会把一个标签从文档树中移除,然后彻底销毁这个标签和它里面的内容。
from bs4 import BeautifulSoup
string = '''
<td>
+421 48/471 78 14
<br />
<em>(bowling)</em>
</td>
'''
soup = BeautifulSoup(string, 'html.parser')
em = soup.select_one('em').decompose()
phone = soup.select_one('td').text.strip()
print(phone)
输出结果:
+421 48/471 78 14
1
这对你有用吗?
>>> 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'
>>>
9
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()
这段代码的意思是:在网页中找到第一个 td
标签,然后获取这个标签里面的内容,接着用 str.strip()
把所有的换行符 \n
去掉。
根据文档中的说明 next_element:
字符串或标签的 .next_element 属性指向紧接着被解析的内容