Intenté encontrar todos los archivos <p> etiquetas dentro de la clase content-inner y no quiero que todas las etiquetas <p> etiquetas que hablan de derechos de autor (las últimas etiquetas <p> fuera de la clase contenedora) que aparecen al filtrar las etiquetas <p> etiquetas y mis imágenes muestran una lista vacía o no sale nada y por lo tanto no se guarda ninguna imagen.
main = requests.get('https://url_on_html.com/')
beautify = BeautifulSoup(main.content,'html5lib')
news = beautify.find_all('div', {'class','jeg_block_container'})
arti = []
for each in news:
title = each.find('h3', {'class','jeg_post_title'}).text
lnk = each.a.get('href')
r = requests.get(lnk)
soup = BeautifulSoup(r.text,'html5lib')
content = [i.text.strip() for i in soup.find_all('p')]
content = ' '.join(content)
images = [i['src'] for i in soup.find_all('img')]
arti.append({
'Headline': title,
'Link': lnk,
'image': images,
'content': content
})
El HTML de este sitio web tiene este aspecto:
<html><head><title>The simple's story</title></head>
<body>
<div class="content-inner "><div class="addtoany_share_save_cont"><p>He added: “The President king administration has embarked on
railway construction</p>
<p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
<script></script>
<p> we will not once in Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
<p>the emergency of our matter is Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
<script></script>
<br></br>
<script></script>
<p>king of our Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
<script></script>
<img src="image.png">
<p>he is our Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
<p>some weas Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p>
</div>
</div>
<div>
<p>Copyright © 2021. All Rights Reserved. Vintage Press Limited. Optimized by <a href="https://inerd360.com/">iNERD360</a></p>
</div>
Esto mostrará una lista vacía:
content = [i.text.strip() for i in soup.find_all('div', {'class', 'content-inner'}]
Además de las imágenes, este código también muestra páginas vacías:
images = [i['src'] for i in soup.find_all('img',)]
Esto filtrará todos los <p> etiquetas en la página HTML y esto es lo que no quiero
content = [i.text.strip() for i in soup.find_all('p')]
¿Cómo filtro todos los archivos <p> etiquetas excepto la última <p> etiquetas fuera de la clase? Además, ¿cómo filtro imágenes correctamente con bs4?
Estoy esperando que alguien me ayude
- Precioso Olufemi
27 de marzo de 2021 a las 8:42
Estimado @CygnusX, ¿cómo soluciono este problema? ¿Cómo elimino estas etiquetas p externas?
- Precioso Olufemi
27/03/2021 a las 21:38
¿Podría proporcionarnos el enlace al sitio web?z
- Jacob Lee
27/03/2021 a las 21:53
Hola@JacobLee, este es el enlace view-source:thenationonlineng.net/…
- Precioso Olufemi
28/03/2021 a las 21:59
Estoy intentando eliminar esa página y elel párrafo con derechos de autor es perturbador y no aparece ninguna imagen
- Precioso Olufemi
28/03/2021 a las 22:00
------------------------------------
Reemplazar: contenido = [i.text.strip() para i en sopa.find_all('p')]
Con:
div_list = [div for div in soup.find_all('div', class_="content-inner")]
p_list = [div.find_all('p') for div in div_list]
content = [item.text.strip() for p in p_list for item in p]
Deje el resto del código sin cambios.
De esta manera, su secuencia de comandos devuelve una lista que contiene todo lo que solicita (incluidas las imágenes), excepto los agregados y la cadena de derechos de autor.
5
Esto insertará anuncios y otras cadenas y no será profesional___ imágenes del código de anuncios de personas que se muestran en sus noticias
- Precioso Olufemi
29/03/2021 a las 21:43
Sería útil saberlo antes. Vea la respuesta actualizada después de su comentario que genera el resultado deseado.
- Laurent
30 de marzo de 2021 a las 6:51
Muchas gracias @Laurent. Esto resolvió el problema de derechos de autor, pero obtuve errores para las imágenes o una nueva excepción si es un archivo y no un archivo._committed: AttributeError: 'list' el objeto no tiene el atributo '_committed' Intenté usar un bucle for y todavía no funcionó. gracias por resolver mis derechos de autor
- Precioso Olufemi
31 de marzo de 2021 a las 1:36
Esto parece ser un problema independiente relacionado con otra parte de tu código, no puedo ayudarte, lo siento.
- Laurent
31 de marzo de 2021 a las 5:12
Si esta o cualquier respuesta ha resuelto su pregunta, considere aceptarla haciendo clic en la marca de verificación. Esto indica a la comunidad en general que has encontrado una solución y otorga cierta reputación tanto a quien responde como a ti mismo. No hay obligación de hacer esto. Si lo desea, también puede agregar +10 puntos a cualquier autor de cualquier buena respuesta haciendo clic en el triángulo gris superior. En cualquier caso, que tengas un buen día.
- Laurent
31 de marzo de 2021 a las 5:16
------------------------------------
Obtener una lista de todos los párrafos
paragraphs = soup.find_all("p")
Produzca una lista filtrada (lista por comprensión) de párrafos que no comiencen con la cadena "Copyright":
paragraphs = [item.text.strip() for item in paragraphs if not item.text.startswith("Copyright")]
2
muchas gracias @anonymous pero las imágenes no funcionan
- Precioso Olufemi
28/03/2021 a las 22:00
Lo siento, todas las sugerencias y respuestas aquí no funcionaron
- Precioso Olufemi
28/03/2021 a las 23:54