python - 需要将抓取的数据写入csv文件(线程)

标签 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',
                  '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/

相关文章:

python - 如何在 python-socketio 上发送消息

python - Popen subprocess.PIPE 及其用途

python - 如何使用numpy生成楼梯编号序列

csv - Netlogo-使用 .csv 文件中的特征创建代理

Python 和向 urllib 请求添加数据的新方法

c++ - 使用 C++ 中的信号更改 std::thread 执行流程

java - 正确停止在 InputStream 的 read() 中阻塞的线程

.net - Interlocked.Xxx 方法是否保证在所有数据缓存中更新值?

postgresql - 您可以根据列值将 Postgres 表导出到多个 CSV 文件吗?

python - 使用用户输入的关键字搜索 CSV 文件中的项目