Python 3.6:csvwriter只写两个第一个字符串

时间:2018-04-29 20:23:02

标签: python csv export-to-csv python-3.6

我正在尝试将足球队名和赔率从网页进行网页划分到csv文件。我的问题是它只将前两个字符串写入csv文件。谁能看到我做错了什么?

当我打印它时,它在picture上看起来很完美,但是当我将它提取到csv文件时它是空的

from selenium import webdriver
from bs4 import BeautifulSoup
import csv

url = "https://1xbet.cm/en/live/Football/"

driver = webdriver.Chrome("C:/Users/Christian/Desktop/WebScraper 0.5/chromedriver/chromedriver.exe")
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')

containers = soup.findAll("div", {"class": "c-events__item_col"})
for container in containers:
    teams = [x.get_text() for x in container.findAll(
        "span", {"class": "c-events__team"}
    )]
    odds = [x.attrs.get('data-coef') for x in container.findAll(
        "a", {"class": "c-bets__bet"}
    )]

    #print(teams)
    #print(odds)
    #print()

# name of csv file
filename = "C:/Users/Christian/Desktop/WebScraper 0.5/1xbetLiveOdds.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    csvwriter.writerow(teams)
    csvwriter.writerow(odds)

1 个答案:

答案 0 :(得分:0)

似乎你想要这样的东西:

from selenium import webdriver
from bs4 import BeautifulSoup
import csv

url = "https://1xbet.cm/en/live/Football/"

driver = webdriver.Chrome("C:/Users/Christian/Desktop/WebScraper 0.5/chromedriver/chromedriver.exe")
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')

containers = soup.findAll("div", {"class": "c-events__item_col"})
teams_odds = []
for container in containers:
    teams_odds.append([x.get_text() for x in container.findAll(
        "span", {"class": "c-events__team"}
    )])
    teams_odds.append([x.attrs.get('data-coef') for x in container.findAll(
        "a", {"class": "c-bets__bet"}
    )])


# name of csv file
filename = "C:/Users/Christian/Desktop/WebScraper 0.5/1xbetLiveOdds.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
    # creating a csv writer object
    csvwriter = csv.writer(csvfile)

    # writing the fields
    for toe in teams_odds:
        csvwriter.writerow(toe)