Как я могу напечатать «напиши мне 1» и «напиши мне 2» из HTML-кода? - PullRequest
0 голосов
/ 22 декабря 2018

Если у меня есть этот HTML-код,

<div class="_1GGPkHIiaumnRMT-S1cU29"><span>print me 1</span><span><div class="_2ZBv5UiBzOiApuonYSpb92"><div>patates</div></div></span><span>print me 2</span></div>

как я могу получить «напиши мне 1» и «напиши мне 2»?

Я изучаю веб-скребинг в Python с помощью BeautifulSoup.

for subcat in category.find_all("div"):
        print(subcat)

1 Ответ

0 голосов
/ 22 декабря 2018

Логика

1) Encapsulate HTML in a single quoted string.
2) Initialize BeautifulSoup
3) Locate all Span tags where presumably only text will occur in between tags
4) Iterate across all returned values (strings) that have span in them
5) If div or any other tag occurs (other tag case not covered in answer) then ignore record
6) Otherwise print value, after removing span tags

Код

#import the Beautiful soup functions to parse the data returned from the website
from bs4 import BeautifulSoup


category = BeautifulSoup('<div class="_1GGPkHIiaumnRMT-S1cU29"><span>print me 1</span><span><div class="_2ZBv5UiBzOiApuonYSpb92"><div>patates</div></div></span><span>print me 2</span></div>')

def printSpan(s):
  s = s.find_all("span")
  for string in s:
    if len(string.find_all("div")) != 0:
      continue
    else:
      print (str(string).replace("<span>", "").replace("</span>", ""))

printSpan(category)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...