2016-09-15 5 views
1

Dies ist meine erste Frage auf Stack-Überlauf so bitte mit mir.Scraping Probleme auf einer bestimmten Website

Ich versuche, automatisch (also schaben), um den Text von einigen italienischen Gesetzen von der Website heruntergeladen werden: http://www.normattiva.it/

ich diesen Code verwenden unten (und ähnliche Permutationen):

import requests, sys 

debug = {'verbose': sys.stderr} 
user_agent = {'User-agent': 'Mozilla/5.0', 'Connection':'keep-alive'} 

url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' 

r = requests.session() 
s = r.get(url, headers=user_agent) 
#print(s.text) 
print(s.url) 
print(s.headers) 
print(s.request.headers) 

Wie Sie kann ich sehen, ich versuche, die "caricaArticolo" Abfrage zu laden.

jedoch die Ausgabe eine Seite ist zu sagen, dass meine Suche ist ungültig („Sitzung ist ungültig oder abgelaufen“)

Es scheint, dass die Seite erkennt, dass ich nicht einen Browser und lädt bin mit eine "Ausbruch" Javascript Funktion.

<body onload="javascript:breakout();"> 

Ich habe versucht, "Browser" Simulator Python-Skripte wie Selen und robobrowser zu verwenden, aber das Ergebnis ist das gleiche.

Gibt es jemanden, der bereit ist, 10 Minuten mit der Ausgabe der Seite zu verbringen und Hilfe zu geben?

+0

@terzin Um auf die Seite zugreifen zu können, benötigen Sie zunächst einen autorisierten Benutzer.Sie haben keine gültige Sitzung. –

+0

Ich habe den gleichen Code versucht und ich bekomme die gewünschte Ausgabe –

+0

Versuchen Sie mit "beesesoup" ist eine sehr leistungsfähige Bibliothek, die tun wird, was Sie brauchen. –

Antwort

1

Einmal klicken Sie einen Link auf der Seite mit Entwickler-Tools öffnen, unter der doc Registerkarte unter Netzwerk:

enter image description here

Sie drei Links sehen können, ist das erste, was wir auf klicken, um die zweite Rückkehr Der HTML-Code, mit dem Sie zu einem bestimmten Artikel springen können und das letzte enthält den Artikeltext.

In der Quelle, aus dem FIRST zurückgegeben, können Sie zwei iframe Tags sehen:

<div id="alberoTesto"> 
     <iframe 
      src="/atto/caricaAlberoArticoli?atto.dataPubblicazioneGazzetta=2016-08-31&atto.codiceRedazionale=16G00182&atto.tipoProvvedimento=DECRETO LEGISLATIVO" 
      name="leftFrame" scrolling="auto" id="leftFrame" title="leftFrame" height="100%" style="width: 285px; float:left;" frameborder="0"> 
     </iframe> 

     <iframe 
      src="/atto/caricaArticoloDefault?atto.dataPubblicazioneGazzetta=2016-08-31&atto.codiceRedazionale=16G00182&atto.tipoProvvedimento=DECRETO LEGISLATIVO" 
      name="mainFrame" id="mainFrame" title="mainFrame" height="100%" style="width: 800px; float:left;" scrolling="auto" frameborder="0"> 
     </iframe> 

Die erste für den Artikel ist, letztere mit /caricaArticoloDefault und die idmainframe ist was wir wollen.

Sie müssen die Cookies von den ersten Anfragen verwenden, so dass Sie es mit der Session tun können Objekt und durch die Seiten-Parsing bs4 mit:

import requests, sys 
import os 
from urlparse import urljoin 
import io 
user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} 

url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' 

with requests.session() as s: 
    s.headers.update(user_agent) 
    r = s.get("http://www.normattiva.it/") 
    soup = BeautifulSoup(r.content, "lxml") 
    # get all the links from the initial page 
    for a in soup.select("div.testo p a[href^=http]"): 
     soup = BeautifulSoup(s.get(a["href"]).content) 
     # The link to the text is in a iframe tag retuened from the previous get. 

     text_src_link = soup.select_one("#mainFrame")["src"] 

     # Pick something to make the names unique 
     with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: 
      # The text is in pre tag that is in the div with the pre class 
      text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ 
       .select_one("div.wrapper_pre pre").text 
      f.write(text) 

Ein Ausschnitt aus der ersten Textdatei:

   IL PRESIDENTE DELLA REPUBBLICA 
    Visti gli articoli 76, 87 e 117, secondo comma, lettera d), della 
Costituzione; 
    Vistala legge 28 novembre 2005, n. 246 e, in particolare, 
l'articolo 14: 
    comma 14, cosi' come sostituito dall'articolo 4, comma 1, lettera 
a), della legge 18 giugno 2009, n. 69, con il quale e' stata 
conferita al Governo la delega ad adottare, con le modalita' di cui 
all'articolo 20 della legge 15 marzo 1997, n. 59, decreti legislativi 
che individuano le disposizioni legislative statali, pubblicate 
anteriormente al 1° gennaio 1970, anche se modificate con 
provvedimenti successivi, delle quali si ritiene indispensabile la 
permanenza in vigore, secondo i principi e criteri direttivi fissati 
nello stesso comma 14, dalla lettera a) alla lettera h); 
    comma 15, con cui si stabilisce che i decreti legislativi di cui 
al citato comma 14, provvedono, altresi', alla semplificazione o al 
riassetto della materia che ne e' oggetto, nel rispetto dei principi 
e criteri direttivi di cui all'articolo 20 della legge 15 marzo 1997, 
n. 59, anche al fine di armonizzare le disposizioni mantenute in 
vigore con quelle pubblicate successivamente alla data del 1° gennaio 
1970; 
    comma 22, con cui si stabiliscono i termini per l'acquisizione del 
prescritto parere da parte della Commissione parlamentare per la 
semplificazione; 
    Visto il decreto legislativo 30 luglio 1999, n. 300, recante 
riforma dell'organizzazione del Governo, a norma dell'articolo 11 
della legge 15 marzo 1997, n. 59 e, in particolare, gli articoli da 
20 a 22; 
+0

danke !!!! siehe unten! – terzim

0

wunderbar, wunderbar, wunderbar Padraic. Es klappt. Ich musste mich nur ein wenig um die Importe kümmern, aber es funktioniert wunderbar. Vielen Dank. Ich entdecke gerade Pythons Potential und Sie haben meine Reise mit dieser speziellen Aufgabe viel einfacher gemacht. Ich hätte es nicht alleine gelöst.

import requests, sys 
import os 
from urllib.parse import urljoin 
from bs4 import BeautifulSoup 
import io 
user_agent = {'User-agent': 'Mozilla/5.0', 'Connection': 'keep-alive'} 

url = 'http://www.normattiva.it/atto/caricaArticolo?art.progressivo=0&art.idArticolo=1&art.versione=1&art.codiceRedazionale=047U0001&art.dataPubblicazioneGazzetta=1947-12-27&atto.tipoProvvedimento=COSTITUZIONE&art.idGruppo=1&art.idSottoArticolo1=10&art.idSottoArticolo=1&art.flagTipoArticolo=0#art' 

with requests.session() as s: 
    s.headers.update(user_agent) 
    r = s.get("http://www.normattiva.it/") 
    soup = BeautifulSoup(r.content, "lxml") 
    # get all the links from the initial page 
    for a in soup.select("div.testo p a[href^=http]"): 
     soup = BeautifulSoup(s.get(a["href"]).content) 
     # The link to the text is in a iframe tag retuened from the previous get. 

     text_src_link = soup.select_one("#mainFrame")["src"] 

     # Pick something to make the names unique 
     with io.open(os.path.basename(text_src_link), "w", encoding="utf-8") as f: 
      # The text is in pre tag that is in the div with the pre class 
      text = BeautifulSoup(s.get(urljoin("http://www.normattiva.it", text_src_link)).content, "html.parser")\ 
       .select_one("div.wrapper_pre pre").text 
      f.write(text)