Herramientas de usuario

Herramientas del sitio


python:webscraping

Diferencias

Muestra las diferencias entre dos versiones de la página.

Enlace a la vista de comparación

Ambos lados, revisión anteriorRevisión previa
Próxima revisión
Revisión previa
python:webscraping [2024/02/05 18:50] – [Encontrar elementos] albertopython:webscraping [2024/02/05 19:00] (actual) – [Encontrar elementos] alberto
Línea 126: Línea 126:
  
 Suponemos el siguiente código HTML Suponemos el siguiente código HTML
-<code HTML>+<code html>
 <!-- This is the example.html example file. --> <!-- This is the example.html example file. -->
 <html><head><title>The Website Title</title></head> <html><head><title>The Website Title</title></head>
Línea 154: Línea 154:
 'Al Sweigart' 'Al Sweigart'
 >>> elems[0].attrs >>> elems[0].attrs
 +{'id': 'author'}
 +>>> pElems = exampleSoup.select('p')
 +>>> str(pElems[0])
 +'<p>Download my <strong>Python</strong> book from <a href="https://
 +inventwithpython.com">my website</a>.</p>'
 +>>> pElems[0].getText()
 +'Download my Python book from my website.'
 +>>> str(pElems[1])
 +'<p class="slogan">Learn Python the easy way!</p>'
 +>>> pElems[1].getText()
 +'Learn Python the easy way!'
 +>>> str(pElems[2])
 +'<p>By <span id="author">Al Sweigart</span></p>'
 +>>> pElems[2].getText()
 +'By Al Sweigart'
 +</code>
 +
 +==== Obtener datos de atributos de elementos ====
 +Para obtener fácilmente los valores de los atributos de un elemento (objeto tipo tag), podemos usar el método **get()**. Se le pasa el string del nombre de un atributo, y devuelve su valor. Vemos un ejemplo en la consola de Python:
 +<code python>
 +>>> import bs4
 +>>> soup = bs4.BeautifulSoup(open('example.html'), 'html.parser')
 +>>> spanElem = soup.select('span')[0]
 +>>> str(spanElem)
 +'<span id="author">Al Sweigart</span>'
 +>>> spanElem.get('id')
 +'author'
 +>>> spanElem.get('some_nonexistent_addr') == None
 +True
 +>>> spanElem.attrs
 {'id': 'author'} {'id': 'author'}
 </code> </code>
 ===== Módulo selenium ===== ===== Módulo selenium =====
python/webscraping.1707155457.txt.gz · Última modificación: por alberto

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki