【问题标题】:Need to write scraped data into csv file (threading)需要将抓取的数据写入 csv 文件(线程)
【发布时间】:2019-07-20 07:34:19
【问题描述】:

这是我的代码:

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

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

【问题讨论】:

  • 您是否尝试过保持文件打开,然后在其上追加内容?

标签: python multithreading csv web-scraping


【解决方案1】:

我认为您应该考虑使用某种queuing 或线程池。 Thread pools 如果您想创建多个线程(不是 4 个,我认为您会使用 4 个以上的线程,但一次使用 4 个线程),则非常有用。

队列技术的一个例子可以在here找到。

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

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

【讨论】:

  • 在我的原始答案中添加了一些示例。
  • 如果你可以编辑我的代码来做到这一点,那就太好了,这些例子似乎很难理解,然后修改为我的实际代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 2020-02-22
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
相关资源
最近更新 更多