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 - 使用OpenCV,Python,Raspberry Pi 3的Ball Tracker

ios - (Swift 3)父子上下文崩溃核心数据(libc++abi.dylib : terminating with uncaught exception of type NSException (Recorded Frame) )

php - 无法将文件 CSV 上传到托管数据库

c - volatile integer 如何解决这个线程同步问题?

python - 用 Pandas 读取 'csv' 文件时解析日期时间

r - 在导出为 .csv 文件之前加入两个数据框

python - 使用 GitPython 列出特定 git 提交的目录内容

python - "UnicodeDecodeError: ' utf-8 ' codec can' t 解码字节 0x80",同时使用 pydrive 在 google colaboratory 上加载 pickle 文件

python - 确定python中两个数据集是否相等的最佳方法?

c++ - 为什么在 CAS 循环失败时首选 std::memory_order_relaxed ?