【发布时间】:2015-04-14 23:13:20
【问题描述】:
我已经构建了一个网络抓取工具,可以提取网站上的所有图像。我的代码应该将每个 img URL 打印到标准输出并写入一个包含所有这些的 csv 文件,但现在它只是将找到的最后一个图像写入文件并将结果的数量写入 csv。
这是我目前使用的代码:
# This program prints a list of all images contained in a web page
#imports library for url/html recognition
from urllib.request import urlopen
from HW_6_CSV import writeListToCSVFile
#imports library for regular expressions
import re
#imports for later csv writing
import csv
#gets user input
address = input("Input a url for a page to get your list of image urls ex. https://www.python.org/: ")
#opens Web Page for processing
webPage = urlopen(address)
#defines encoding
encoding = "utf-8"
#defines resultList variable
resultList=[]
#sets i for later printing
i=0
#defines logic flow
for line in webPage :
line = str(line, encoding)
#defines imgTag
imgTag = '<img '
#goes to next piece of logical flow
if imgTag in line :
i = i+1
srcAttribute = 'src="'
if srcAttribute in line:
#parses the html retrieved from user input
m = re.search('src="(.+?)"', line)
if m:
reline = m.group(1)
#prints results
print("[ ",[i], reline , " ]")
data = [[i, reline]]
output_file = open('examp_output.csv', 'w')
datawriter = csv.writer(output_file)
datawriter.writerows(data)
output_file.close()
webPage.close()
如何让这个程序将找到的所有图像写入 CSV 文件?
【问题讨论】:
-
对象
data,在倒数第7行声明,只包含一行。 -
@bernie 那么如何让它识别 reline 中的所有数据?
-
@Celeo 抱歉,我正在尝试打印所有数据
标签: python csv web-scraping