2016-09-15 136 views
1

這是我在堆棧溢出問題上的第一個問題,請耐心等待。在特定網站上刮掉問題

我試圖從網站上自動下載(即刮)的一些意大利的法律文本:http://www.normattiva.it/

我使用下面這段代碼(以及類似排列):

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) 

正如你可以看到我正在嘗試加載「caricaArticolo」查詢。

然而,輸出的是一個網頁說,我的搜索是無效的(「會話無效或過期」

看來,網頁承認我不使用瀏覽器和負載一個「突破」的JavaScript功能。

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

我試圖用「瀏覽器」模擬器Python腳本,例如robobrowser但結果是一樣的。

有沒有人願意花10分鐘看頁面輸出並給予幫助?

+0

@terzin要訪問您首先需要授權的用戶的頁面。你沒有有效的會話。 –

+0

我試了相同的代碼,我得到所需的輸出 –

+0

嘗試使用「beautifulsoup」它真正強大的庫,將做你所需要的。 –

回答

1

一旦你點擊網絡下使用開發工具打開的網頁上的任何鏈接,該文檔選項卡下:

enter image description here

你可以看到三個環節,第一個就是我們點擊,第二個返回該HTML允許您跳轉到特定的文章,最後一頁包含文章文字。

在從首聯返回的源代碼,你可以看到兩個IFRAME標籤:

<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> 

首先是項目,後者與/caricaArticoloDefaultIDmainFrame中是我們想要的。

你需要從最初的請求使用Cookie,這樣您可以與會議對象,並通過分析網頁使用bs4做到這一點:

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) 

第一個文本文件中的一個片段:

   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

謝謝!!!!見下文! – terzim

0

精彩,美妙,精彩的Padraic。有用。剛剛不得不略微編輯清除進口,但它的作品奇妙。非常感謝。我只是發現了python的潛力,並且通過這個特定的任務,你使我的旅程變得更加輕鬆。我不會一個人解決它。

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)