首页 > 解决方案 > 需要将抓取的数据写入 csv 文件(线程)

问题描述

这是我的代码:

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 文件。我不确定我可以在函数中打开文件,因为线程会同时多次打开文件。

注意:我知道在爬行时线程是不可取的,但我只是在测试

标签: pythonmultithreadingcsvweb-scraping

解决方案


我认为您应该考虑使用某种排队或线程池。如果您想创建多个线程(不是 4 个,我认为您将使用超过 4 个线程,但一次使用 4 个线程),线程池非常有用。

可以在此处找到队列技术的示例。

当然,您可以使用线程 id 标记文件,例如:“results_1.txt”、“results_2.txt”等。然后,您可以在所有线程完成后合并它们。

您可以使用 Lock、Monitor 等基本概念,但我不是它们的最大粉丝。可以在此处找到锁定示例


推荐阅读