python - for循環(huán)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)’’’輸出百度搜索結(jié)果數(shù)據(jù):當前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的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.b3g6.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出正確結(jié)果,但是我希望能生成csv報表文件,嘗試修改for為函數(shù)失敗。小菜鳥一枚,不知道怎么搞了,求大神指點
問題解答
回答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)’’’輸出百度搜索結(jié)果數(shù)據(jù):當前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的url),標題’’’# 保存標題result_csv_writer.writerow([’關(guān)鍵詞’, ’排名’, ’排名網(wǎng)站’, ’百度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.b3g6.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()
代碼未測試,有問題請簡單修改
相關(guān)文章:
1. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務器還是不能訪問?4. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?5. 實現(xiàn)bing搜索工具urlAPI提交6. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化7. javascript - nodejs關(guān)于進程間發(fā)送句柄的一點疑問8. phpstudy8.1支持win11系統(tǒng)嗎?9. 如何解決Centos下Docker服務啟動無響應,且輸入docker命令無響應?10. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~

網(wǎng)公網(wǎng)安備