如何在现有的Excel文件中写入Web抓取的数据?

时间:2019-06-11 10:25:31

标签: excel web-scraping python-3.7

我写了一个代码到网上刮擦统计足球的桌子上,并将每一行都放在列表中。现在,我想将此数据放在现有的excel文件和确定的工作表中。 我的excel文件有很多工作表,我有一个工作表是用于存储这些数据的,但是我不知道该怎么做。 由于我的代码抓取了2个表,因此我希望这两个表在excel工作表中彼此相邻,中间有2个空列。 我在Internet上做了一些研究,但不幸的是没有任何帮助。

我尝试使用openpyxl,xlwt,我对熊猫做了一些尝试,但是由于我没有太多的知识,所以没有找到解决方案。 我正在使用Mac。

 from selenium import webdriver
 from bs4 import BeautifulSoup
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.support import expected_conditions as ec
 import time
 import pandas as pd

 # Open web page
 driver = webdriver.Firefox(executable_path='/Applications/Python 3.7/geckodriver')
 driver.get('https://www.whoscored.com/Regions/108/Tournaments/5/Italy-Serie-A')

 # Premi Continua per utilizzare il sito
 element=WebDriverWait(driver,20).until(ec.element_to_be_clickable((By.XPATH,"//button[contains(.,'Continue Using Site')]")))
 driver.execute_script("arguments[0].click();", element)
 time.sleep(3)

# Push Standings and Form
options_group_list = []
block_options = driver.find_element_by_xpath('//*[@id="tournament-tables- 16548-options"]')
all_options = block_options.find_elements_by_tag_name('a')[0:2]

for options in all_options:
     options_group_list.append(options)

for option in options_group_list:
     option.click()
     time.sleep(3)

     # Push on wide
     filter_button = driver.find_element_by_link_text("Wide")
     filter_button.click()
     time.sleep(3)

     # page source
     source = driver.page_source
     soup = BeautifulSoup(source, 'lxml')

     # find table and rows
     table = soup.find('table', {"id": "standings-16548-grid"})
     rows = table.find_all('tr')[2]

     # setting columns
     columns = [v.text for v in rows.find_all('th')]
     print(columns)

     # Data
     table_rows = table.find_all('tr')
     for row in table_rows[5:len(table_rows)]:
         row_list = []
         for data in row.find_all('td'):
            row_list.append(data.text)
         print(row_list)

0 个答案:

没有答案