logo

Leer el contenido de la página web seleccionada usando Python Web Scraping

Requisito previo: Descarga de archivos en Python Raspado web con BeautifulSoup Todos sabemos que Python es un lenguaje de programación muy sencillo, pero lo que lo hace interesante es la gran cantidad de bibliotecas de código abierto escritas para él. Requests es una de las bibliotecas más utilizadas. Nos permite abrir cualquier sitio web HTTP/HTTPS y hacer cualquier tipo de cosas que normalmente hacemos en la web y también puede guardar sesiones, es decir, cookies. Como todos sabemos, una página web es solo un fragmento de código HTML que el servidor web envía a nuestro navegador, que a su vez se convierte en una hermosa página. Ahora necesitamos un mecanismo para obtener el código fuente HTML, es decir, encontrar algunas etiquetas particulares con un paquete llamado BeautifulSoup. Instalación:
pip3 install requests 
pip3 install beautifulsoup4 

Tomemos un ejemplo leyendo un sitio de noticias. Tiempos del Indostán

El código se puede dividir en tres partes.
  • Solicitar una página web
  • Inspeccionando las etiquetas
  • Imprima el contenido apropiado
Pasos:
    Solicitar una página web:Primero vemos hacer clic derecho en el texto de la noticia para ver el código fuente. Leer el contenido de la página web seleccionada usando Python Web Scraping' title= Inspeccionando las etiquetas:Necesitamos determinar en qué cuerpo del código fuente se encuentra la sección de noticias que queremos eliminar. Es la lista desordenada de uli.e 'searchNews' la que contiene la sección de noticias. Leer el contenido de la página web seleccionada usando Python Web Scraping' title= Nota El texto de la noticia está presente en la parte del texto de la etiqueta de anclaje. Una observación cercana nos da la idea de que todas las noticias están en las etiquetas de la lista li de la etiqueta desordenada. Leer el contenido de la página web seleccionada usando Python Web Scraping' title= Imprima el contenido apropiado: The content is printed with the help of code given below. Python
    import requests from bs4 import BeautifulSoup def news(): # the target we want to open  url='http://www.hindustantimes.com/top-news' #open with GET method resp=requests.get(url) #http_respone 200 means OK status if resp.status_code==200: print('Successfully opened the web page') print('The news are as follow :-n') # we need a parserPython built-in HTML parser is enough . soup=BeautifulSoup(resp.text'html.parser') # l is the list which contains all the text i.e news  l=soup.find('ul'{'class':'searchNews'}) #now we want to print only the text part of the anchor. #find all the elements of a i.e anchor for i in l.findAll('a'): print(i.text) else: print('Error') news() 

    Producción

    Successfully opened the web page The news are as follow :- Govt extends toll tax suspension use of old notes for utility bills extended till Nov 14 Modi Abe seal historic civil nuclear pact: What it means for India Rahul queues up at bank says it is to show solidarity with common man IS kills over 60 in Mosul victims dressed in orange and marked 'traitors' Rock On 2 review: Farhan Akhtar Arjun Rampal's band hasn't lost its magic Rumours of shortage in salt supply spark panic among consumers in UP Worrying truth: India ranks first in pneumonia diarrhoea deaths among kids To hell with romance here's why being single is the coolest way to be India vs England: Cheteshwar Pujara Murali Vijay make merry with tons in Rajkot Akshay-Bhumi SRK-Alia Ajay-Parineeti: Age difference doesn't matter anymore Currency ban: Only one-third have bank access; NE backward regions worst hit Nepal's central bank halts transactions with Rs 500 Rs 1000 Indian notes Political upheaval in Punjab after SC tells it to share Sutlej water Let's not kid ourselves with Trump what we have seen is what we will get Want to colour your hair? Try rose gold the hottest hair trend this winter 

Referencias



Crear cuestionario