4

我正在尝试使用requestsbeautifulsoup4从这里下载一堆 pdf 文件。这是我的代码:

import requests
from bs4 import BeautifulSoup as bs

_ANO = '2013/'
_MES = '01/'
_MATERIAS = 'matematica/'
_CONTEXT = 'wp-content/uploads/' + _ANO + _MES
_URL = 'http://www.desconversa.com.br/' + _MATERIAS + _CONTEXT

r = requests.get(_URL)
soup = bs(r.text)

for i, link in enumerate(soup.findAll('a')):
    _FULLURL = _URL + link.get('href')

    for x in range(i):
        output = open('file[%d].pdf' % x, 'wb')
        output.write(_FULLURL.read())
        output.close()

我得到AttributeError: 'str' object has no attribute 'read'

好的,我知道,但是...如何从生成的 URL 下载?

4

3 回答 3

8

这会将页面中的所有文件及其原始文件名写入一个pdfs/目录。

import requests
from bs4 import BeautifulSoup as bs
import urllib2


_ANO = '2013/'
_MES = '01/'
_MATERIAS = 'matematica/'
_CONTEXT = 'wp-content/uploads/' + _ANO + _MES
_URL = 'http://www.desconversa.com.br/' + _MATERIAS + _CONTEXT

# functional
r = requests.get(_URL)
soup = bs(r.text)
urls = []
names = []
for i, link in enumerate(soup.findAll('a')):
    _FULLURL = _URL + link.get('href')
    if _FULLURL.endswith('.pdf'):
        urls.append(_FULLURL)
        names.append(soup.select('a')[i].attrs['href'])

names_urls = zip(names, urls)

for name, url in names_urls:
    print url
    rq = urllib2.Request(url)
    res = urllib2.urlopen(rq)
    pdf = open("pdfs/" + name, 'wb')
    pdf.write(res.read())
    pdf.close()
于 2013-09-27T19:48:41.303 回答
6

使用 可能会更容易wget,因为如果需要,您将拥有wget 的全部功能(用户代理、关注、忽略 robots.txt ...):

import os

names_urls = zip(names, urls)

for name, url in names_urls:
    print('Downloading %s' % url)
    os.system('wget %s' % url)
于 2014-07-24T08:34:08.713 回答
1

我已采用 samstav 的回答来使用 Python3 - 另外在我的示例中不需要使用 urllib2。

from bs4 import BeautifulSoup
import requests

baseurl = "https://www.debian.org"
path = "/releases/stable/releasenotes"
_URL = baseurl + path

r = requests.get(_URL)

soup = BeautifulSoup(r.text)
urls = []
names = []
for i, link in enumerate(soup.findAll("a")):
    _FULLURL = (baseurl + str(link.get("href")))
    if _FULLURL.endswith(".pdf"):
        urls.append(_FULLURL)
        names.append(soup.select("a")[i].attrs["href"])

names_urls = zip(names, urls)

for name, url in names_urls:
    print(url)
    r = requests.get(url)
    with open("pdfs//" + name.split('/')[-1], "wb") as f:
        f.write(r.content)
于 2021-08-18T14:22:13.387 回答