【问题标题】:OSError: [Errno 22] Invalid argument for open()OSError: [Errno 22] open() 的参数无效
【发布时间】:2017-05-03 17:31:43
【问题描述】:
import requests
from bs4 import BeautifulSoup


url = input("URL:")
grab_page = requests.get(url)
parse_page = BeautifulSoup(grab_page.text, "html.parser")
file_name = parse_page.title.string.replace("\\,()", "")


newfile = open(file_name + ".html", "w+")
newfile.write(grab_page.text)

当我尝试运行上述代码时,this particular URL, 网页的标题是“如何安装 JDK 8(在 Windows 上, Mac OS、Ubuntu)和 Java 编程入门”我收到以下错误:

Traceback (most recent call last):
  File "C:/Users/LKT/PycharmProjects/webpagegrabber/main.py", line 12, in <module>
    newfile = open(file_name + ".html", "w+")
OSError: [Errno 22] Invalid argument: 'How to Install JDK 8 (on Windows,\r\nMac OS, Ubuntu) 
    and Get Started with Java Programming.html'

我哪里做错了?

【问题讨论】:

  • 您将'How to Install JDK 8 (on Windows,\r\nMac OS, Ubuntu) and Get Started with Java Programming.html' 传递给open,根据您的操作系统,这不是有效路径。

标签: python replace beautifulsoup


【解决方案1】:

您的文件名包含无效字符(\n\r)。所以你不能在 Windows 中创建这样的文件。如Windows Developer Center中所述:

整数表示在 1 范围内的字符 到 31,除了这些字符的备用数据流 被允许。有关文件流的更多信息,请参阅文件 流。

【讨论】:

  • 我尝试用 .replace() 函数替换这些字符。知道为什么它不起作用吗?
  • 它没有出现在您的代码中,但我会检查是否还有其他偷偷摸摸的无效字符(也许也将文件名打印为十六进制字符串)
  • 特别是这行代码:file_name = parse_page.title.string.replace("\\,()", "") 然后我尝试将它作为 open() 的参数传递跨度>
  • 你没有替换 '\n' 和 '\r' 那里。如果你想替换它们,你应该调用 replace('\n', '').replace('\r', '')
  • also - replace 不将正则表达式作为参数,因此它只会替换出现的整个字符串
猜你喜欢
  • 2019-04-27
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 2017-04-10
  • 2021-02-10
  • 2021-11-06
相关资源
最近更新 更多