![](/img/trans.png)
[英]Printing no output to a text file in python while reading specific lines
[英]python : empty output is printing while reading the web browser output
我的文件中有一組 URL 鏈接,我需要打開每個鏈接並獲取輸出,我需要將其存儲在一個文件中。 但是如果我試圖打印輸出空行就會出現。 請找到下面的代碼並幫助我解決這個問題
import urllib2
import webbrowser
with open('C:\\Users\\home\\Desktop\\11.txt','r') as fp:
for line in fp:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "https://facebook.com"
password_mgr.add_password(None, top_level_url, "appsdev", "--omitted--")
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
r=opener.open(top_level_url)
r.read()
print r.read()
如果您發布的代碼是正確的,並且第二個r.read()
不是錯字,那是因為您有兩次讀取。
在類文件對象(如opener.open()
的返回值)上,調用read()
將返回整個內容並將當前位置設置為文件末尾。 對read()
后續調用將返回空字符串,因為光標已經位於文件末尾。
在你的代碼中
r.read() # This returns the entire contents
print r.read() # Empty string
去掉第一個r.read()
。
在寫入其他文件之前,將該內容分配給任何變量,
喜歡 ,
out_data = r.read()
new_file = open('file.txt','w')
new_file.write(out_data)
new_file.close()
就是這樣,您抓取的數據將被寫入file.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.