【问题标题】:Determining number of sites on a website in python在python中确定网站上的站点数量
【发布时间】:2011-03-13 16:57:49
【问题描述】:

我有以下链接:

http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0001&language=EN

url的引用部分有如下信息:

A7 == 议会(当前为第七届议会,前者为A6,以此类推)

2010 == 年

0001 == 文件编号

对于每年和议会,我想确定网站上的文件数量。任务很复杂,例如,对于 2010 年,数字 186、195,196 有空页,而最大数字是 214。理想情况下,输出应该是一个包含所有文档编号的向量,不包括丢失的文档编号。

谁能告诉我这在 python 中是否可行?

最好的,托马斯

【问题讨论】:

    标签: python url web-scraping


    【解决方案1】:

    首先,确保抓取他们的网站是合法的。

    其次,请注意,当文档不存在时,HTML 文件包含:

    <title>Application Error</title>
    

    第三,使用 urllib 遍历所有你想要的东西:

    for p in range(1,7):
     for y in range(2000, 2011):
      doc = 1
      while True:
        # use urllib to open the url: (root)+p+y+doc
        # if the HTML has the string "application error" break from the while
        doc+=1
    

    【讨论】:

    • 谢谢,很有帮助! The site is public (these are our elected parliamentarians after all :)) so i guess the legal aspect should not be an issue.
    【解决方案2】:

    这是一个解决方案,但在请求之间添加一些超时是个好主意:

    import urllib
    URL_TEMPLATE="http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-%d-%.4d&language=EN"
    maxRange=300
    
    for year in [2010, 2011]:
        for page in range(1,maxRange):
            f=urllib.urlopen(URL_TEMPLATE%(year, page))
            text=f.read()
            if "<title>Application Error</title>" in text:
                print "year %d and page %.4d NOT found" %(year, page)
            else:
                print "year %d and page %.4d FOUND" %(year, page)
            f.close()
    

    【讨论】:

    • 非常感谢,这里的所有答案都是很好的例子!
    【解决方案3】:

    这是一个稍微更完整(但很老套)的示例,它似乎可以工作(使用 urllib2)——我相信您可以根据您的特定需求对其进行自定义。

    我还要重复 Arrieta 的警告,即确保网站所有者不介意您抓取其内容。

    #!/usr/bin/env python
    import httplib2
    h = httplib2.Http(".cache")
    
    parliament = "A7"
    year = 2010
    
    #Create two lists, one list of URLs and one list of document numbers.
    urllist = []
    doclist = []
    
    urltemplate = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=%s-%d-%04u&language=EN"
    
    for document in range(0,9999):
        url = urltemplate % (parliament,year,document)
        resp, content = h.request(url, "GET")
        if content.find("Application Error") == -1:
            print "Document %04u exists" % (document)    
            urllist.append(urltemplate % (parliament,year,document))
            doclist.append(document)
        else:
            print "Document %04u doesn't exist" % (document)
    print "Parliament %s, year %u has %u documents" % (parliament,year,len(doclist))
    

    【讨论】:

    • 感谢 Jon 非常详尽的回答,这对于学习 python 的人来说是个好东西!
    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多