2 回答
TA贡献1815条经验 获得超13个赞
以追加模式打开一个文件,并将每个文件的输出写入其中。
import urllib2
from bs4 import BeautifulSoup
quote_page = 'https://www.example.com/page/1024'
#Rest of the script here
output = open("output.txt", 'a') # 'a' means open in append mode so the file is not overwritten
# change print to output.write()
output.write(str(var1) + '\n') # separate each var by a new line
output.write(str(var2) + '\n')
output.write(str(var3) + '\n')
output.close()
这将写入所有 var1,然后是所有 var2,然后是所有 var3,每个都以空行分隔,然后关闭文件。
为了使其更兼容从命令行接受 url:
import sys
import urllib2
from bs4 import BeautifulSoup
quote_page = sys.argv[1] # this should be the first argument on the command line
#Rest of the script here
output = open("output.txt", 'a') # 'a' means open in append mode so the file is not overwritten
# change print to output.write()
output.write(str(var1) + '\n') # separate each var by a new line
output.write(str(var2) + '\n')
output.write(str(var3) + '\n')
output.close()
使用您的 url 的示例命令行:
$python3.6 myurl.py https://www.example.com/page/1024
TA贡献1818条经验 获得超8个赞
要从您的文件中获取 url,您需要打开它,然后为每一行运行您的脚本。假设每一行有一个 url。要写入输出文件,请打开一个文件并将 var1、var2 和 var3 写入其中
import urllib2
from bs4 import BeautifulSoup
with open('url.txt') as input_file:
for url in input_file:
quote_page = url
#Rest of the script here
with open("ouput_file.txt", "w") as output:
output.write(f'{var1}\n')
output.write(f'{var2}\n')
output.write(f'{var3}\n')
添加回答
举报