python - for循環print怎樣才能輸出csv呢
問題描述
import csv,redef search(req,line): text = re.search(req,line) if text:data = text.group(1) else:data = ’no’ return datacsvfile = file(’serp_html.csv’,’rb’)reader = csv.reader(csvfile)’’’輸出百度搜索結果數據:當前關鍵詞,排名,排名網站,百度url(需轉義后才是真實的url),標題’’’for line in reader: word = line[0] html = line[1] number = search(r’id='(d+)'’,html) domain = search(r’<span class='g'>(.*?)/.*</span>’,html) bdurl = search(r’href='http://m.piao2010.com/wenda/(http://www.baidu.com/link?url=[^']*?)'’,html) title = search(r’'title':'([^']*?)'’,html) print ’%s,%s,%s,%s,%s’ % (word,number,domain,bdurl,title)
以上是一個繼承程序,運行后能print出正確結果,但是我希望能生成csv報表文件,嘗試修改for為函數失敗。小菜鳥一枚,不知道怎么搞了,求大神指點
問題解答
回答1:可以這樣
import csv,redef search(req,line): text = re.search(req,line) if text:data = text.group(1) else:data = ’no’ return datareuslts = []result_csv = file(’new_file.csv’, ’wb’)result_csv_writer = csv.writer(result_csv)’’’輸出百度搜索結果數據:當前關鍵詞,排名,排名網站,百度url(需轉義后才是真實的url),標題’’’# 保存標題result_csv_writer.writerow([’關鍵詞’, ’排名’, ’排名網站’, ’百度url’, ’標題’]) for line in reader: word = line[0] html = line[1] number = search(r’id='(d+)'’,html) domain = search(r’<span class='g'>(.*?)/.*</span>’,html) bdurl = search(r’href='http://m.piao2010.com/wenda/(http://www.baidu.com/link?url=[^']*?)'’,html) title = search(r’'title':'([^']*?)'’,html) reuslts.append((word, number, domain, bdurl, title)) # print ’%s,%s,%s,%s,%s’ % (word,number,domain,bdurl,title)# 保存多行result_csv_writer.writerows(reuslts)result_csv.close()
代碼未測試,有問題請簡單修改
相關文章:
1. ddos - apache日志很多其它網址,什么情況?2. 怎么在phpstudy中用phpexcel上傳數據到MYSQL?3. javascript - 百度搜索網站,如何讓搜索結果顯示一張圖片加上一段描述,如圖;求教4. vue.js - centos 使用vue-cli. 執行npm run dev 報錯5. php由5.3升級到5.6后,登錄網站,返回的是php代碼,不是登錄界面,各位大神有知道的嗎?6. 發現了多個名稱為[spring_web]的片段。相對順序不合法7. android - 使用vue.js進行原生開發如何進行Class綁定8. docker綁定了nginx端口 外部訪問不到9. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?10. html5和Flash對抗是什么情況?
