久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

python - for循環(huán)print怎樣才能輸出csv呢

瀏覽:148日期:2022-09-02 13:06:21

問題描述

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ù):當(dāng)前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的url),標(biāo)題’’’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://www.baoyu77737.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ù):當(dāng)前關(guān)鍵詞,排名,排名網(wǎng)站,百度url(需轉(zhuǎn)義后才是真實的url),標(biāo)題’’’# 保存標(biāo)題result_csv_writer.writerow([’關(guān)鍵詞’, ’排名’, ’排名網(wǎng)站’, ’百度url’, ’標(biāo)題’]) 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://www.baoyu77737.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()

代碼未測試,有問題請簡單修改

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 沾益县| 辽源市| 共和县| 宣恩县| 武强县| 三明市| 林州市| 都昌县| 宿松县| 东台市| 通道| 万宁市| 南乐县| 卓资县| 芒康县| 鄂托克旗| 萨嘎县| 阜阳市| 怀安县| 鹤山市| 宜兰县| 宁国市| 湘阴县| 水富县| 舟曲县| 开鲁县| 绥化市| 巴彦淖尔市| 韶山市| 双牌县| 开江县| 百色市| 随州市| 长泰县| 长乐市| 澄城县| 西充县| 宜春市| 尖扎县| 如东县| 墨竹工卡县|