修复python3.5上的FTP webscraping脚本

2024-05-12 13:47:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从FTP服务器中提取一个文本文件。这是我已有的代码:

from ftplib import FTP
import re

def my_function(data):
    print(data)

ftp = FTP('ftp.nasdaqtrader.com')
ftp.login()
nasdaq=ftp.retrbinary('RETR /SymbolDirectory/nasdaqlisted.txt', my_function)
#nasdaq contains the text file

我对这种方法有几个问题。例如,每次我运行脚本时,所有我确实不想要的东西都打印出来,我只需要将变量“nasdaq”存储为一个字符串。此外,即使“纳斯达克”打印出这一行:

b'Symbol|Security Name|Market Category|Test Issue|Financial Status|Round Lot Size|ETF|NextShares\r\nAAAP|Advanced Accelerator Applications S.A. - American Depositary Shares

我无法证明它在纳斯达克:

print ("\r\nAAAP|Advanced Accelerator Applications S.A." in nasdaq)
Out: False

哪种方法更像Python?你知道吗


Tags: 方法import服务器datamyftpfunctionadvanced
1条回答
网友
1楼 · 发布于 2024-05-12 13:47:37

这实际上是Is it possible to read FTP files without writing them using Python?的一个副本,但我想展示如何具体地实现它。你知道吗

from ftplib import FTP
from io import BytesIO

data = BytesIO()
with FTP("ftp.nasdaqtrader.com") as ftp: # use context manager to avoid
    ftp.login()                          # leaving connection open by mistake
    ftp.retrbinary("RETR /SymbolDirectory/nasdaqlisted.txt", data.write)
data.seek(0) # need to go back to the beginning to get content
nasdaq = data.read().decode() # convert bytes back to string

nasdaq现在应该是一个包含指定文件内容的字符串,带有\r\nWindows样式的行结尾。如果对这两个字符进行.split(),则会得到一个列表,其中每行都是一个组件。你知道吗

相关问题 更多 >