【发布时间】:2019-07-20 07:34:19
【问题描述】:
这是我的代码:
from download1 import download
import threading,lxml.html
def getInfo(initial,ending):
for Number in range(initial,ending):
Fields = ['country', 'area', 'population', 'iso', 'capital', 'continent', 'tld', 'currency_code',
'currency_name', 'phone',
'postal_code_format', 'postal_code_regex', 'languages', 'neighbours']
url = 'http://example.webscraping.com/places/default/view/%d'%Number
html=download(url)
tree = lxml.html.fromstring(html)
results=[]
for field in Fields:
x=tree.cssselect('table > tr#places_%s__row >td.w2p_fw' % field)[0].text_content()
results.append(x)#should i start writing here?
downloadthreads=[]
for i in range(1,252,63): #create 4 threads
downloadThread=threading.Thread(target=getInfo,args=(i,i+62))
downloadthreads.append(downloadThread)
downloadThread.start()
for threadobj in downloadthreads:
threadobj.join() #end of each thread
print "Done"
所以results 将具有Fields 的值,我需要将Fields 的数据作为顶行(仅一次)然后将results 中的值写入CSV 文件。
我不确定我是否可以在函数中打开文件,因为线程会同时多次打开文件。
注意:我知道在爬行时线程是不可取的,但我只是在测试
【问题讨论】:
-
您是否尝试过保持文件打开,然后在其上追加内容?
标签: python multithreading csv web-scraping