Python 需要将刮取的数据写入csv文件(线程化)
这是我的密码:Python 需要将刮取的数据写入csv文件(线程化),python,multithreading,csv,web-scraping,Python,Multithreading,Csv,Web Scraping,这是我的密码: 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',
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"
因此,结果
将具有字段的值
,我需要将字段
作为顶行写入数据(仅一次),然后将结果
中的值写入CSV文件。
我不确定是否可以在函数中打开该文件,因为线程将同时打开该文件多次
注意:我知道在爬行时线程是不可取的,但我只是在测试我想你应该考虑使用某种线程池。如果您想要创建多个线程(不是4个,我认为您将使用4个以上的线程,但一次使用4个线程),则这些线程非常有用 可以找到队列技术的一个示例 当然,您可以用线程id标记文件,例如:“results_1.txt”、“results_2.txt”等等。然后,可以在所有线程完成后合并它们
您可以使用锁、监视器等基本概念,但我不是它们的忠实粉丝。可以找到一个锁定示例您是否尝试过将文件保持打开状态,然后将其附加到文件上?在我的原始答案中添加了一些示例。如果您可以编辑我的代码来执行此操作,那就太好了,这些示例似乎很难理解,然后修改为我的实际代码