python - 不在python中写入文件

标签 python python-2.7 file web-scraping

我正在使用 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/

相关文章:

android - 将 ImageView 保存到特定文件夹中的图像

python - 在 Bokeh 中在线性和对数刻度之间切换

python - 如何在 python 中进行 fork 或非阻塞系统调用

python - 使用 conftest.py 与从专用模块导入固定装置

python - 从头开始将字符串转换为大写

python - 在保留引号的同时用 nltk 拆分句子

linux - 如何在linux中查找包含字符串的行

python - 脚本从许多内容中获取更少的内容

python - 列表理解的多重赋值

javascript - node.js/socket.io如何分离html的javascript?