简体   繁体   English

不在python中写入文件

[英]Not writing to file in python

I am using selenium to scrape a website and I have stored all the links in a.txt.我正在使用 selenium 来抓取网站,并将所有链接存储在 a.txt 中。 Now, I wish to scrape individual links from each of those websites and write to b.txt.现在,我希望从每个网站上抓取单独的链接并写入 b.txt。 problem is, my code does not write to the second and file and I do not know why.问题是,我的代码没有写入第二个和文件,我不知道为什么。 I am printing the scrapped values to the console and it works perfectly fine.我正在将报废的值打印到控制台,它工作得很好。 It just doesn't write to the file b.txt它只是不写入文件 b.txt

Any ideas what Could've gone wrong?任何想法可能出了什么问题? Below is my code.下面是我的代码。

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()

Do you mean that your code only writes the first time around (looks like some typo in your question that confuses me a bit), but if thats the case, maybe you need to append你的意思是你的代码只写了第一次(看起来你的问题中有一些错字让我有点困惑),但如果是这样,也许你需要附加

open(file1, 'a')

instead of代替

open(file1, 'r')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM