iT邦幫忙

0

[Python][BeautifulSoup][CSV] 將爬取四組網頁資料寫入csv . 只顯示最後一組

使用python爬取資料..讀取的網址共有2個
但把列印的結果 輸出 csv ,只會顯示最後1各結果 為何?

import requests
from bs4 import BeautifulSoup
import csv
for i in range(12,14):
for q in range(1,2):
url ="https://bwfbadminton.com/rankings/2/bwf-world-rankings/6/men-s-singles/20"+str(i)+"/"+str(q)+"/?rows=25&page_no=1"
print(url.format(i,q))
res=requests.get(url.format(i,q))
soup=BeautifulSoup(res.text)
with open('test.csv','w',encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(['date','country','player','point'])
for i in range(0,25):
dd=soup.body.find_all("option",selected=True)[1].text
date=dd[8:18]
country=soup.tbody.find_all("div","country")[i].text.strip()
player=soup.tbody.find_all("div","player")[i].text.strip()
point=soup.tbody.find_all("strong")[i].text.strip()
p1,p2=point.split('/')
writer.writerow([date,country,player,p1])

to 一級屠豬士

sorry 這跟我的程式碼 顯示結果一樣 只會顯示25筆 無法把四個網站100筆都顯示出來

感謝! 把 W 改成 a 對初學者 最容易
也感謝 點出 q in range(1,2) 語法上的錯誤

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
4
lulu_meat
iT邦研究生 5 級 ‧ 2020-12-07 10:13:24
最佳解答

你這一行的'w'意思是: 如果檔案存在,覆蓋舊的資料,寫入新的資料。

with open('test.csv','w',encoding="utf-8") as f:

所以在跑完25次時再寫入時會從檔案開頭開始覆寫
可以改成這樣試試看:

with open('test.csv','a',encoding="utf-8") as f:
1
一級屠豬士
iT邦大師 1 級 ‧ 2020-12-06 22:20:59

程式碼先貼好,把你的情況說明好吧.別人沒那樣多時間還要去摸索.
你自己整理的越清楚,得到正確解答的機會越高.

for i in range(0,25): 
這樣就執行 25 次 啊. 
1
ccutmis
iT邦高手 2 級 ‧ 2020-12-07 11:49:35

建議改用requests_html 比bs更好用 相關教學可以自行google 'requests_html'
另外樓主對 range的用法有些誤區,比如說 i in range(1,2),i不會是1跟2,只會是1,
range()第二個參數是stop,舉個例 [i for i in range(0,5)] 結果就是:
[0,1,2,3,4]
所以你在本文里寫的 for q in range(1,2): 只會執行 q=1 也就是一次
我改成 for q in range(1,3): 就會執行 q=1 跟 q=2 ,這個應該不難理解。
以下是完整範例: (註:需先安裝requests_html模組 pip install requests_html)

import time,csv
from requests_html import HTMLSession

session=HTMLSession()

with open('test.csv', 'w+', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Date', 'Country', 'Player', 'Point'])
    for i in range(12,14):
        for q in range(1,3):
            url ="https://bwfbadminton.com/rankings/2/bwf-world-rankings/6/men-s-singles/20"+str(i)+"/"+str(q)+"/?rows=25&page_no=1"
            print(url)
            r=session.get(url)
            date_txt=r.html.find('#ranking-week option[selected="selected"]', first=True).text.split("(")[1].replace(")","")
            country_list=r.html.find('div.country')
            player_list=r.html.find('div.player span a')
            point_list=r.html.find('td.point strong')

            for z in range(0,len(player_list)):
                writer.writerow([ date_txt,country_list[z].text,player_list[z].text.strip(),point_list[z].text.split("/")[0].strip() ])
            #網頁爬虫適時讓伺服器喘口氣是種美德
            print("爬取web寫入CSV檔...休息3秒。")
            time.sleep(3)
print("爬取web寫入CSV檔...完成!")

爬完結果: test.csv

Date,Country,Player,Point
2012-01-05,MAS,LEE Chong Wei,"95,947"
2012-01-05,CHN,LIN Dan,"93,226"
...
2013-01-10,INA,Dionysius Hayom RUMBAKA,"42,242"
2013-01-10,HKG,WONG Wing Ki Vincent,"42,017"

我要發表回答

立即登入回答