我正在尝试创建一个包含 URL 列表的 CSV 文件。
我对编程很陌生,所以请原谅任何草率的代码。
我有一个循环,它遍历位置列表以获取 URL 列表。
然后我在该循环中有一个循环,将数据导出到 CSV 文件。
import urllib, csv, re
from BeautifulSoup import BeautifulSoup
list_of_URLs = csv.reader(open("file_location_for_URLs_to_parse"))
for row in list_of_URLs:
row_string = "".join(row)
file = urllib.urlopen(row_string)
page_HTML = file.read()
soup = BeautifulSoup(page_HTML) # parsing HTML
Thumbnail_image = soup.findAll("div", {"class": "remositorythumbnail"})
Thumbnail_image_string = str(Thumbnail_image)
soup_3 = BeautifulSoup(Thumbnail_image_string)
Thumbnail_image_URL = soup_3.findAll('a', attrs={'href': re.compile("^http://")})
Run Code Online (Sandbox Code Playgroud)
这是对我不起作用的部分:
out = csv.writer(open("file_location", "wb"), delimiter=";")
for tag in soup_3.findAll('a', href=True):
out.writerow(tag['href'])
Run Code Online (Sandbox Code Playgroud)
基本上作者一直在写自己,有没有办法跳到 CSV 上的第一个空行下方并开始写作?
不要把它放在任何循环中:
out = csv.writer(open("file_location", "wb"), delimiter=";")
Run Code Online (Sandbox Code Playgroud)
反而:
with open("file_location", "wb") as fout:
out = csv.writer(fout, delimiter=";")
# put for-loop here
Run Code Online (Sandbox Code Playgroud)
笔记:
open("file_location", "wb")
创建一个新文件,销毁任何同名的旧文件。这就是为什么看起来作者正在覆盖旧行的原因。with open(...) as ...
因为它会在with-block
结束时自动为您关闭文件。这在文件关闭时明确。否则,文件将保持打开状态(可能不会完全刷新),直到out
被删除或重新分配给新值。这不是你的主要问题,但使用with
太有用了,更不用说。