0

我正在尝试使用 Python3.7中 urllib.request 模块中的 urlretrieve 从此ASPX站点及其文件夹下载一堆 xls 文件。首先,我用站点中的 url 构建了一个 txt 文件。然后,根据这里的解决方案,我遍历列表并要求服务器检索 xls 文件。

该算法开始下载工作目录中的 xls 文件,但经过 3 或 4 次迭代后,它就破解了。下载的文件(3 个或 4 个)大小不正确(例如,所有文件都是 7351Kb,而不是 99Kb 或 83Kb)。令人惊讶的是,这是 txt 文件中最后一个 url 的大小。

有时,日志会发送一条带有 500 错误的消息。

对于最后一个问题,我的假设/问题是:

  1. 由于防火墙阻止重复调用服务器而引发错误

  2. 也许这些调用违反了我不知道的异步/异步规则。我使用 time.sleep 来防止错误,但它失败了。

第一个问题太奇怪了,它被链接到第二个问题。

这是我的代码:

import os
import time    
from random import randint
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from urllib.request import urlopen, urlretrieve, quote    



url="http://informacioninteligente10.xm.com.co/transacciones/Paginas/HistoricoTransacciones.aspx"
        u = urlopen(url)
        try:
            html = u.read().decode('utf-8')
        finally:
            u.close()
direcciones = [] #to be populated with urls

soup = BeautifulSoup(html)
for link in soup.select('div[webpartid] a'):
    href = link.get('href')
    if href.startswith('javascript:'):
        continue
    filename = href.rsplit('/', 1)[-1]

    href = urljoin(url, quote(href))
    #try:
    #    urlretrieve(href, filename)
    #except:
    #    print('Downloading Error')
    
    if any (href.endswith(x) for x in ['.xls','.xlsx','.csv']):
        direcciones.append(href)

# "\n"  adds a new line
direcciones = '\n'.join(direcciones)


#Save every element in a txt file
with open("file.txt", "w") as output:
     output.write(direcciones) 


DOWNLOADS_DIR = os.getcwd()

# For every line in the file
for url in open("file.txt"):
    time.sleep(randint(0,5))

    # Split on the rightmost / and take everything on the right side of that
    name = url.rsplit('/', 1)[-1]

    # Combine the name and the downloads directory to get the local filename
    filename = os.path.join(DOWNLOADS_DIR, name)
    filename = filename[:-1] #Quitamos el espacio en blanco al final

    # Download the file if it does not exist
    if not os.path.isfile(filename):
        urlretrieve(href, filename)

我没有使用正确的 url 解析器吗?

有任何想法吗?谢谢!

4

1 回答 1

0

它有反机器人,你需要设置浏览器用户代理而不是默认的 python 用户代理

......
import urllib.request

opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0')]
urllib.request.install_opener(opener)

url=....

你必须替换hrefurlin

if not os.path.isfile(filename):
    urlretrieve(href, filename) # must be: url
于 2018-11-09T08:59:17.870 回答