简体   繁体   English

Python Selenium 列表导出到文本文件

[英]Python Selenium List Export to text file

The code below was intended to get the titles of the video courses.下面的代码旨在获取视频课程的标题。 Well it finds it, but I am unable to write the output to a text file.好吧,它找到了,但我无法将 output 写入文本文件。

from selenium import webdriver
f=("output.txt", "a")

browsing_1 = webdriver.Firefox(executable_path="C:\\Tester\\geckodriver.exe")
browsing_1.get("https://channel9.msdn.com/Niners/JeffKoch/Posts?page=170")

testing_texts = browsing_1.find_elements_by_xpath("//div[@class='seriesTitle']")
for namess in testing_texts:
    print(namess.text)

When I use this f.write(names) it gives out the below:当我使用这个 f.write(names) 时,它会给出以下内容:

Traceback (most recent call last):
  File "C:\Tester\trial83.py", line 11, in <module>
    f.write(names)
AttributeError: 'tuple' object has no attribute 'write'

Is there anyway that I can append the file and have the below output in it please?无论如何,我可以 append 文件并在其中包含以下 output 吗?

Link:"https://channel9.msdn.com/Niners/JeffKoch/Posts?page=170"
System Center 2012 R2 Infrastructure Provisioning and Management
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Core Solutions of Exchange Server 2013
Windows Server 2012 R2 Storage
Windows Server 2012 R2 Storage
Windows Server 2012 R2 Storage
Windows Server 2012 R2 Storage

I used a list to store all the values of the scraped data, and then converted that list to .txt file.我使用一个list来存储抓取数据的所有值,然后将该列表转换为.txt文件。

from selenium import webdriver

browsing_1 = webdriver.Firefox(executable_path="C:\\Users\\intel\\Downloads\\Setups\\geckodriver.exe")
browsing_1.get("https://channel9.msdn.com/Niners/JeffKoch/Posts?page=170")

testing_texts = browsing_1.find_elements_by_xpath("//div[@class='seriesTitle']")

# created an empty list
lis = []
for namess in testing_texts:
    print(namess.text)
    lis.append(namess.text)   # appending that empty list to store further values

print(lis)

#remember to add a full correct path to your file just like i did.   
with open(r'C:\Users\intel\Desktop\output.txt', 'a') as f:   
    for item in lis:
        f.write("%s\n" % item)

It worked just perfectly.它工作得很好。 Try this.尝试这个。 Hope it's the desired output that you want.希望这是您想要的 output。

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

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