繁体   English   中英

抓取特定网站上的问题

[英]Scraping issues on a specific website

这是我关于堆栈溢出的第一个问题,请耐心等待。

我试图从网站上自动下载(即刮取)一些意大利法律的文本: 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 脚本,例如seleniumrobobrowser,但结果是一样的。

有没有人愿意花10分钟看页面输出并提供帮助?

在打开开发工具的页面上单击任何链接后,在网络下的文档选项卡下:

在此处输入图片说明

您可以看到三个链接,第一个是我们点击的内容,第二个返回允许您跳转到特定文章的 html,最后一个包含文章文本。

在firstlink返回的源码中,可以看到两个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>

第一个用于文章,后者带有/caricaArticoloDefaultid mainFrame是我们想要的。

您需要使用初始请求中的 cookie,以便您可以使用Session对象并使用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;

美妙,美妙,美妙的帕德莱克。 有用。 只需要稍微编辑以清除导入,但它的效果非常好。 非常感谢。 我只是在发现 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM