3 回答

TA貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
您的for loop縮進(jìn)不正確。正確的縮進(jìn)是:
for price_text in price_texts:
team = name_text.div.text
odds = price_text.span.text
team = name_text.div.text
odds = price_text.span.text
print(odds)
print(team + odds)
f.write(team + "," + odds + "\n")
f.close()
隊(duì)前有 4 個(gè)空格和賠率。請閱讀Python ForLoop 文檔。
此外,沒有price_texts變量。當(dāng)你做findAll時(shí)你需要分配它,你忘記了一個(gè)'S':
price_texts = soup.findAll("div",{"class":"priceText_f71sibe"})
最后一件事,考慮使用with而不是open()和.close()寫入您的文件。

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
你能試試這個(gè)嗎?
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
my_url = 'https://www.sportsbet.com.au/betting/basketball-us'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
soup = BeautifulSoup(page_html, "html.parser")
price_texts = soup.findAll("div",{"class":"priceText_f71sibe"})
name_texts = soup.findAll("div",{"class":"size14_f7opyze Endeavour_fhudrb0 medium_f1wf24voparticipantText_fivg86r"})
filename = "odds.csv"
f = open(filename,"w")
headers = "Team, odds_team\n"
print(name_text)
f.write(headers)
odds =''
team=''
for price_text in price_texts:
odds = price_text.text
for name_text in name_texts:
team = name_text.text
print(odds)
print(team + odds)
f.write(team + "," + odds + "\n")
f.close()

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
我在想你可以做的只是迭代并將它們存儲(chǔ)到列表中,然后寫入文件。不幸的是,我無法在工作中訪問該站點(diǎn),因此無法測試代碼,但我相信這應(yīng)該會(huì)提供您正在尋找的輸出:
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq
import csv
from itertools import zip_longest
my_url = 'https://www.sportsbet.com.au/betting/basketball-us'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
soup = BeautifulSoup(page_html, "html.parser")
price_text = soup.findAll("span",{"data-automation-id":"price-text"})
name_text = soup.findAll("div",{"data-automation-id":"participant-one"})
team_list = [ name.text.strip() for name in name_text ]
odds_list = [ price.text.strip() for price in price_text ]
d = [team_list, odds_list]
export_data = zip_longest(*d, fillvalue = '')
with open('odds.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
wr = csv.writer(myfile)
wr.writerow(("Team", "odds_team"))
wr.writerows(export_data)
myfile.close()
添加回答
舉報(bào)