这是我的代码:
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文件。我不确定我是否可以在函数中打开文件,因为线程会同时多次打开文件。
注意:我知道抓取时不希望使用线程,但我只是在测试
最佳答案
我认为您应该考虑使用某种queuing或线程池。如果您想创建多个线程(而不是4个,我想您一次要使用4个以上的线程,但是一次要使用4个线程),那么Thread pools确实很有用。
可以从here找到一个队列技术的例子。
当然,您可以使用其线程ID标记文件,例如:“results_1.txt”,“results_2.txt”等等。然后,您可以在所有线程完成后合并它们。
您可以使用“锁”,“监视器”等基本概念,但是我不是它们的忠实拥护者。锁定的示例可以在here中找到
关于python - 需要将抓取的数据写入csv文件(线程),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890912/