Eu estou tentando baixar o texto de um site de notícias. O HTML é:
<div class="pane-content">
<div class="field field-type-text field-field-noticia-bajada">
<div class="field-items">
<div class="field-item odd">
<p>"My Text" target="_blank">www.injuv.cl</a></strong></p> </div>
A saída deve ser: My Text Eu estou usando o seguinte código python:
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
html = "My URL"
parsed_html = BeautifulSoup(html)
p = parsed_html.find("div", attrs={"class":"pane-content"})
print(p)
Mas a saída do código é: "None". Você sabe o que está errado com o meu código?
Respostas:
2 para resposta № 1O problema é que você não está analisando o HTML, você está analisando a string de URL:
html = "My URL"
parsed_html = BeautifulSoup(html)
Em vez disso, você precisa obter / recuperar / baixar a fonte primeiro, exemplo em Python 2:
from urllib2 import urlopen
html = urlopen("My URL")
parsed_html = BeautifulSoup(html)
No Python 3, seria:
from urllib.request import urlopen
html = urlopen("My URL")
parsed_html = BeautifulSoup(html)
Ou, você pode usar o estilo "para humanos" de terceiros requests
biblioteca:
import requests
html = requests.get("My URL").content
parsed_html = BeautifulSoup(html)
Observe também que você não deve estar usando BeautifulSoup
versão 3 em tudo - não é mais mantido. Substituir:
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
com apenas:
from bs4 import BeautifulSoup
0 para resposta № 2
BeautifulSoup
aceita uma string de HTML. Você precisa recuperar o HTML da página usando o URL.
Confira urllib para fazer solicitações HTTP. (Ou solicitações de para uma maneira ainda mais simples.) Recupere o HTML e passe aquele para BeautifulSoup
igual a:
import urllib
from bs4 import BeautifulSoup
# Get the HTML
conn = urllib.urlopen("http://www.example.com")
html = conn.read()
# Give BeautifulSoup the HTML:
soup = BeautifulSoup(html)
A partir daqui, apenas analise como você tentou anteriormente.
p = soup.find("div", attrs={"class":"pane-content"})
print(p)