python - 需要将抓取的数据写入 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 文件。我不确定我可以在函数中打开文件,因为线程会同时多次打开文件。
注意:我知道在爬行时线程是不可取的,但我只是在测试
解决方案
推荐阅读
- excel - 使用 VBA 将文本从网站拉入 Excel
- node.js - 如何循环运行 selenium web 抓取脚本并将结果发送到 mongodb
- r - 查找分隔字符串中两个子字符串的字符数
- ios - SwiftUI 拖动、放大和缩放手势组合在一起
- mysql - 有没有更好的方法来获得多个计数?
- curl - Youtube Data API v3 - 搜索列表 API - 不指定 channelId 不返回视频
- javascript - 有没有办法从另一个 php 脚本返回的 ajax 数据创建一个 php 变量
- python - 从两个变量创建和采样联合分布
- java - JAVA导入同时使用正则表达式解决
- python - 将 SQLite 表中的数据加载到 PyQt5 tableWidget 中