#python #regex #beautifulsoup #whitespace
#python #регулярное выражение #beautifulsoup #пробел
Вопрос:
У меня есть строка, которая принадлежит переменной tbody, как показано ниже:
tbody =
'...
</td>
<td class="Details clearfix">
<div>
<b>
9. I want this text and number
</b>
</div>
</td>
<td class="flux">
...'
>print type(tbody)
<type 'str'>
Как вы, возможно, уже видели, есть пробел.
Я пытался получить ‘9. Я хочу, чтобы этот текст и число ‘ использовали следующий код:
tbody2 = str(tbody.split(','))
tbody2 = str(re.split('n|r|t', tbody2))
m = re.findall(re.compile("\\n(. ?)\\"), tbody2)
print m
Это результат, который я получаю:
[...'<td class="Details clearfix">', '<div>', '<b>',
'\', '9. I want this text and number', '\', ' </b>', '</div>',
'</td>', '<td class="flux>'...]
Я не смог получить строку, так есть ли способ получить ее, возможно, с помощью BS или regex? Приветствия
Ответ №1:
from bs4 import BeautifulSoup
tbody = """
<td class="Details clearfix">
<div>
<b>
9. I want this text and number
</b>
</div>
</td>
"""
soup = BeautifulSoup(tbody)
for item in soup.find_all('td',class_="Details clearfix"):
print item.div.b.text.strip()
#output= 9. I want this text and number
я думаю, что нет необходимости разделять, вы получаете ожидаемый результат с помощью поиска в beautiful soup
Ответ №2:
Вы могли бы сделать это через модуль re Python, используя модификатор DOTALL,
>>> import re
>>> m = re.search(r'<td.*?>.*?<b>s*([^n]*).*</b>.*?</td>', tbody, re.DOTALL)
>>> m.group(1)
'9. I want this text and number'