【发布时间】:2018-04-09 20:32:07
【问题描述】:
脚本的输入是一个文本文件,其中包含来自网页的多个 url。脚本中的预期步骤如下:
- 从文本文件中读取一个url
- 剥离 url 以将其用作输出文件的名称 (fname)
- 使用正则表达式“clean_me”清理 url/web 页面的内容。
- 将内容写入文件(fname)
- 对输入文件中的每个文件重复。
这是输入文件urloutshort.txt的内容;
这是脚本:
import os
import sys
import requests
import bs4
from bs4 import BeautifulSoup
import html5lib
import re
def clean_me(htmldoc):
soup = BeautifulSoup(htmldoc.text.encode('UTF-8'), 'html5lib')
for s in soup(['script', 'style']):
s.decompose()
return ' '.join(soup.stripped_strings)
with open('urloutshort.txt', 'r') as filein:
for url in filein:
page = requests.get(url.strip())
fname=(url.replace('http://',' '))
fname = fname.replace ('/',' ')
print (fname)
cln = clean_me(page)
with open (fname +'.txt', 'w') as outfile:
outfile.write(cln +"\n")
这是错误信息;
python : Traceback (most recent call last):
At line:1 char:1
+ python webpage_A.py
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
File "webpage_A.py", line 43, in <module>
with open (fname +'.txt', 'w') as outfile:
OSError: [Errno 22] Invalid argument: ' feedproxy.google.com ~r autonews ColumnistsAndBloggers ~3 6HV2TNAKqGk
diesel-with-no-nox-emissions-it-may-be-possible\n.txt'
问题似乎与从文本文件中读取 url(s) 有关,因为如果我绕过脚本来读取输入文件并且只是硬编码其中一个 url,那么脚本将处理网页并将结果保存到从 url 中提取名称的 txt 文件。我搜索了关于 SO 的主题,但没有找到解决方案。
我们将非常感谢您对这个问题的帮助。
【问题讨论】: