Python请求抛出错误IOError:[Errno 22]无效模式(' wb')或文件名:

时间:2017-05-17 08:41:45

标签: python web-scraping python-requests

写作路径是:

  

write_path =' C:\ Users \ hgdht \ Desktop \ Downloader_Automation'

我收到以下错误:

IOError: [Errno 22] invalid mode ('wb') or filename: 'ciarb_annual_review_2011_c
.pdf?sfvrsn=2'

以下是代码:

import os
import csv
import requests

write_path = r'C:\Users\hgdht\Desktop\Downloader_Automation'  # ASSUMING THAT FOLDER EXISTS!

with open('final.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile)
    for link in spamreader:
        print('-'*72)
        print(link)
        pdf_file = link[0].split('/')[-1]
        with open(os.path.join(write_path, pdf_file), 'wb') as pdf:
            try:
                # Try to request PDF from URL
                print('TRYING {}...'.format(link[0]))
                a = requests.get(link[0], stream=True)
                for block in a.iter_content(512):
                    if not block:
                        break

                    pdf.write(block)
                print('OK.')
            except requests.exceptions.RequestException as e:  # This will catch ONLY Requests exceptions
                print('REQUESTS ERROR:')
                print(e)  # This should tell you more details about the error

1 个答案:

答案 0 :(得分:1)

因为您的保存名称中有一些特殊字符。尝试清除它们并使用_删除空格或任何其他字符。可能这会对你有帮助。