我正在使用 selenium 来抓取网站,并且我已将所有链接存储在 a.txt 中。现在,我希望从每个网站上抓取单独的链接并写入 b.txt。问题是,我的代码没有写入第二个和文件,我不知道为什么。我正在将抓取的值打印到控制台,它工作得很好。它只是不写入文件 b.txt
有什么可能出错的想法吗?下面是我的代码。
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()
最佳答案
你的意思是你的代码只在第一次写(看起来你的问题中有一些错字让我有点困惑),但如果是这样的话,也许你需要追加
open(file1, 'a')
代替
open(file1, 'r')
关于python - 不在python中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46728882/