2 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
以追加模式打開一個(gè)文件,并將每個(gè)文件的輸出寫入其中。
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,每個(gè)都以空行分隔,然后關(guān)閉文件。
為了使其更兼容從命令行接受 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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
要從您的文件中獲取 url,您需要打開它,然后為每一行運(yùn)行您的腳本。假設(shè)每一行有一個(gè) url。要寫入輸出文件,請打開一個(gè)文件并將 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')
添加回答
舉報(bào)