python把第x列數(shù)據(jù)寫入第x個(gè)文件
問(wèn)題描述
Python爬蟲一共需要爬取65頁(yè)數(shù)據(jù),每頁(yè)數(shù)據(jù)的列數(shù)不確定。現(xiàn)在我能把每一列的數(shù)據(jù)抓下來(lái),但是因?yàn)榱袛?shù)不確定,寫入的文件名就不能確定。問(wèn)題在于怎么才能把第x列數(shù)據(jù)寫入第x個(gè)文件。也就是如何才能動(dòng)態(tài)選擇file=的文件名。代碼如下:
f_1 = open(’fitment/1.txt’, ’a’)f_2 = open(’fitment/2.txt’, ’a’)f_3 = open(’fitment/3.txt’, ’a’)for i in range(66): pr = random.choice(proxy) url = ’https://*****’ + str(i) + ’****’ page_url = requests.get(url, headers=head, proxies=pr) page_get = page_url.text page_text = BeautifulSoup(page_get, ’lxml’) fitment_1 = page_text.find_all(’tr’, {’class’: ’fitment listRowEven’}) for each_tag_1 in fitment_1:td_text_1 = each_tag_1.find_all(’td’)for x in range(len(td_text_1)+1): print(td_text_1[x].string, file=)
網(wǎng)頁(yè)的結(jié)構(gòu)類如下,每個(gè)tr標(biāo)簽即為一列,具體要抓取的數(shù)據(jù)位于每個(gè)td標(biāo)簽內(nèi)
<tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td></tr><tr> <td>...</td> <td>...</td> <td>...</td> <td>...</td></tr>
問(wèn)題解答
回答1:先不要定義好open文件對(duì)象,可以根據(jù)列數(shù)打開相應(yīng)的文件操作
with open(’列數(shù).txt’, ’a’) as f: f.write(’內(nèi)容’)
相關(guān)文章:
1. MySQL的聯(lián)合查詢[union]有什么實(shí)際的用處2. 數(shù)組排序,并把排序后的值存入到新數(shù)組中3. mysql 遠(yuǎn)程連接出錯(cuò)10060,我已經(jīng)設(shè)置了任意主機(jī)了。。。4. 網(wǎng)頁(yè)爬蟲 - python 爬取網(wǎng)站 并解析非json內(nèi)容5. 默認(rèn)輸出類型為json,如何輸出html6. python的正則怎么同時(shí)匹配兩個(gè)不同結(jié)果?7. mysql怎么表示兩個(gè)字段的差8. win10 python3.5 matplotlib使用報(bào)錯(cuò)9. PHP訂單派單系統(tǒng)10. php多任務(wù)倒計(jì)時(shí)求助
