Имена файлов обрезаются при загрузке в папку - PullRequest
0 голосов
/ 08 января 2020

Мой текущий код вырезает первые 6 символов из имен файлов при загрузке PDF. Так, например, имя файла PDF - 123456acII.pdf (https://example.com/wp-content/uploads/2016/11/123456acII.pdf), но файл в папке - acII.pdf.

Как сделать имена такими, какие они есть?

import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup

main = "https://example.com/"

#If there is no such folder, the script will create one automatically
folder_location = r'C:\temp\webscraping'
if not os.path.exists(folder_location):os.mkdir(folder_location)


def Get_Links():
    r = requests.get(main).text
    soup = BeautifulSoup(r, 'html.parser')
    links = []
    for item in soup.findAll("div", {'class': 'large-4 medium-4 columns'}):
        for n in item.find_all('a'): 
            print ('Link: '+ n.get('href'))
            links.append(n.get('href'))
    return links


def Parse_Links():
    pdf = set()
    for url in Get_Links():
        r = requests.get(url).text
        soup = BeautifulSoup(r, 'html.parser')
        for item in soup.findAll("div", {'class': 'large-6 medium-8 columns large-centered'}):
            for link in item.findAll("a"):
                link = link.get("href")
                if link:
                    pdf.add(link)
    return pdf


def Save():
    for item in Parse_Links():
        print(f"Downloading File: {item[55:]}")
        filename = os.path.join(folder_location,f"{item[55:]}")
        r = requests.get(item)
        with open(filename, 'wb') as f:
            f.write(r.content)
    print("done")


Save()

1 Ответ

1 голос
/ 09 января 2020

Похоже, что вы нарезаете строку, начиная с позиции индекса 55 {item[55:]}. Попытайтесь понять, просто ли это просто начать индексную позицию на 6 позиций раньше:

изменить на: {item[49:]}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...