2017-10-13 90 views
2

我使用硒刮刮一個網站,我已經存儲在a.txt中的所有鏈接。現在,我希望從每個網站中獲取單個鏈接並寫入b.txt。問題是,我的代碼不寫入第二個文件,我不知道爲什麼。我正在將報廢的值打印到控制檯,它工作得很好。它只是不寫入文件b.txt不寫入文件在python

任何想法可能會出錯?以下是我的代碼。

from selenium import webdriver 
from selenium.webdriver.support.wait import WebDriverWait 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support import expected_conditions as EC 

file1 = 'a.txt' 
file2 = 'b.txt' 
xpath = '//*[@id="jw"]/div[2]/video' 
driver = webdriver.Chrome() 
videos = [] 
j = 0 
so = open(file2, 'w') 
with open(file1, 'r') as fo: 
    for url in fo: 
     driver.get(url) 
     wait = EC.presence_of_element_located((By.XPATH, xpath)) 
     WebDriverWait(driver, 5).until(wait) 
     video = driver.find_element_by_xpath(xpath) 
     link = str(video.get_attribute('src')) 
     so.write(link + '\n') 
     videos.append(link) 
     j += 1 
     print j 
     print link 
     print videos 
so.close() 
+0

之前'so.close添加一個換行符()' – Thomas

+0

如何將一個新的在線幫助? @ user1 – krishna

+0

嗯,我試着在控制檯上完全一樣,你做了什麼...不要問我爲什麼...但它的工作。 ¯\ _(ツ)_/ – Thomas

回答

1

你的意思是你的代碼只有大約寫在第一時間(看起來像你的問題的一些錯字,混淆我有點),但如果多數民衆贊成的情況下,也許你需要追加

open(file1, 'a') 

代替

open(file1, 'r') 
+0

Nah。我已經編寫了另一個收集a.txt中的URL的代碼。這是代碼的第二部分,我嘗試使用從a.txt中的第一個代碼中收集的鏈接來抓取網頁以獲取b.txt中的新數據 – krishna