Texto de Python que analiza entre dos palabras
Estoy usando beautifulsoup y quiero extraer todo el texto de entre dos palabras en una página web.
Por ejemplo, imagina el siguiente texto del sitio web:
This is the text of the webpage. It is just a string of a bunch of stuff and maybe some tags in between.
Quiero sacar todo lo que hay en la página que comienza context
y termina conbunch
.
En este caso me gustaría solo:
text of the webpage. It is just a string of a bunch
Sin embargo, existe la posibilidad de que haya varias instancias de esto en una página.
¿Cuál es la mejor manera de hacer esto?
Esta es mi configuración actual:
#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
mech = Browser()
urls = [
http://ca.news.yahoo.com/forget-phoning-business-app-sends-text-instead-100143774--sector.html
]
for url in urls:
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
text= soup.prettify()
texts = soup.findAll(text=True)
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
# If the parent of your element is any of those ignore it
return False
elif re.match('<!--.*-->', str(element)):
# If the element matches an html tag, ignore it
return False
else:
# Otherwise, return True as these are the elements we need
return True
visible_texts = filter(visible, texts)
# Filter only returns those items in the sequence, texts, that return True.
# We use those to build our final list.
for line in visible_texts:
print line