Как я могу получить img-элемент и текст в span-блок? - PullRequest
1 голос
/ 03 июня 2019

У меня есть блок span, подобный этому:

<span class="selectable-text invisible-space copyable-text" dir="ltr">
     some text
     <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>
     more some text
     <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>
     blah-blah-blah
     <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>
</span>
soup.find('span', {'class': 'selectable-text invisible-space copyable-text'}).get_text()

Этот код дает мне только текст.

Все, что я думал о

span = soup.select('span', {'class': 'selectable-text invisible-space copyable-text'})
for item in span:
    if re.match('.*emoji', str(item)):
        ...

Теперь у меня есть такая строка:

<span class="selectable-text invisible-space copyable-text" dir="ltr">some text <img alt="?" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="?" src="URL" style="background-position: -20px -20px;"/>more some text<img alt="?" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="?" src="URL" style="background-position: -40px -40px;"/> blah-blah-blah  <img alt="?" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="?" src="URL" style="background-position: 0px -20px;"/></span>

Мне кажется, что следующим шагом будет использование регулярных выражений для получения нужных мне элементов.

Есть ли еще какие-нибудьспособ получить строку вроде:

some text <emoji> more some text <emoji> blah-blah-blah <emoji>

Ответы [ 3 ]

0 голосов
/ 03 июня 2019

Похоже, вам нужно .replaceWith.

Пример:

from bs4 import BeautifulSoup

html = """<span class="selectable-text invisible-space copyable-text" dir="ltr">
     some text
     <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>
     more some text
     <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>
     blah-blah-blah
     <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>
</span>"""

soup = BeautifulSoup(html, "html.parser")
for span in soup.findAll('span', {'class': 'selectable-text invisible-space copyable-text'}):
    for img in span.findAll("img"):
        img.replaceWith(r"<emoji>")
print(soup.prettify(formatter=None))

Выход:

<span class="selectable-text invisible-space copyable-text" dir="ltr">
 some text
 <emoji>
 more some text
 <emoji>
 blah-blah-blah
 <emoji>
</span>
0 голосов
/ 03 июня 2019

Найдите детей внутри тега Span и затем используйте previous_element, что является текстовым значением.

from bs4 import BeautifulSoup
data='''<span class="selectable-text invisible-space copyable-text" dir="ltr">
     some text
     <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>
     more some text
     <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>
     blah-blah-blah
     <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>
</span>'''

soup=BeautifulSoup(data,'html.parser')
itemtag=soup.find('span', class_='selectable-text invisible-space copyable-text')
children = itemtag.findChildren()
items=[]
for child in children:
  items.append(child.previous_element.replace('\n','').strip())
  items.append(child)

print(items)

Вывод:

['some text', <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>, 'more some text', <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>, 'blah-blah-blah', <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>]
0 голосов
/ 03 июня 2019

Если вы хотите извлечь текст и img в промежуток, тогда код ниже должен работать.

from bs4 import BeautifulSoup as bs

stra = """
<span class="selectable-text invisible-space copyable-text" dir="ltr">
     some text
     <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>
     more some text
     <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>
     blah-blah-blah
     <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>
</span>
"""
soup = bs(stra, 'html.parser')

ch = list(soup.find('span', {'class': 'selectable-text invisible-space copyable-text'}).children)

for i in zip(ch[::2], ch[1::2]):
    print('<span>{}{}</span>'.format(*i))

Вывод:

<span>
     some text
     <img alt="" class="b61 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -20px -20px;"/>
</span>
<span>
     more some text
     <img alt="" class="b62 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: -40px -40px;"/>
</span>
<span>
     blah-blah-blah
     <img alt="" class="b76 emoji wa selectable-text invisible-space copyable-text" data-plain-text="" src="URL" style="background-position: 0px -20px;"/>
</span>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...