Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python urllib2查询–;为一系列URL中的每个网页下载单独的xml文件_Python_Xml_Web Scraping_Urllib2 - Fatal编程技术网

Python urllib2查询–;为一系列URL中的每个网页下载单独的xml文件

Python urllib2查询–;为一系列URL中的每个网页下载单独的xml文件,python,xml,web-scraping,urllib2,Python,Xml,Web Scraping,Urllib2,我是Python新手,如果这是一个非常愚蠢的问题,我深表歉意,但我花了很多时间试图自己回答,但没有成功。我使用以下脚本从使用urllib2的网站下载xml文件: import os os.chdir('C:\Users\AB\Documents') import urllib2 site= "http://www.example.com/ab/cdef/1324" hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/

我是Python新手,如果这是一个非常愚蠢的问题,我深表歉意,但我花了很多时间试图自己回答,但没有成功。我使用以下脚本从使用urllib2的网站下载xml文件:

import os
os.chdir('C:\Users\AB\Documents')
import urllib2
site= "http://www.example.com/ab/cdef/1324"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',}
req = urllib2.Request(site, headers=hdr)
try:
    page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.fp.read()
content = page.read()
filename = "1324.xml"
file_ = open(filename, 'w')
file_.write(content)
file_.close()
我想做的是使用一个脚本从同一个站点下载一系列xml文件。url序列再简单不过了,“”后面的数字每次只增加一个,因此下一个要下载的页面将是“”,生成的文件将被称为“1325.xml”


我尝试了许多不同的FOR循环,但都没有成功。我如何浏览一系列网页,比如说“../cdef/1324”到“../cdef/1340”,并为每个网页下载不同的xml文件(本例中为“1324.xml”到“1340.xml”)

也许它应该有用

import os
import urllib2

os.chdir('C:\Users\AB\Documents')

site= "http://www.example.com/ab/cdef/" # without 1324

hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',}

for number in range(1324, 1341):
    url = site + str(number)
    req = urllib2.Request(url, headers=hdr)
    try:
        page = urllib2.urlopen(req)
    except urllib2.HTTPError, e:
        print e.fp.read()       
    content = page.read()
    filename = str(number) + ".xml"
    file_ = open(filename, 'w')
    file_.write(content)
    file_.close()

你是一个很棒的人。工作得很好。你让一个非常非常沮丧的人非常非常快乐。祝你一切顺利。