【发布时间】:2020-10-20 04:01:45
【问题描述】:
我是 Python 的初学者。我知道现在这是意大利面条代码。请忽略我对 Regex 的野蛮使用来格式化一些数据,这将是我的下一篇文章。
但是,我正在尝试从网站上抓取 Texas Hold 'Em 手牌排名并将其输出到 Excel 文件中,以便使用 ctrl F 轻松搜索它们。
网站上的表格没有用 HTML 编码,所以我决定使用 BeautifulSoup 来抓取这些信息。
到目前为止,我已经设法将数据从字符串转换为列表。当我将它导出到 Excel 时,它会将整行放在同一列单元格中,当它应该用卡片分隔时,获胜概率等逐行..
如何格式化这些数据以使每一行都显示在它自己的单元格中?我有一个想法,使用 for 循环遍历手牌列表及其所有信息,但我不知道如何区分不同的标题,例如卡片、获胜概率等。到目前为止,我使用过正则表达式格式化数据以便于拆分,这是单独的变量。
网站表格是我希望如何在 Excel 中显示数据的一个很好的例子:https://wizardofodds.com/games/texas-hold-em/6-player-game/
from bs4 import BeautifulSoup
import requests
import re
import xlsxwriter
url = "https://wizardofodds.com/games/texas-hold-em/6-player-game/"
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")
def getContent():
table_data = soup.find(class_ = "box-content has-data").get_text()
handRegex1 = re.sub("Pair of ", "", table_data)
handRegex2 = re.sub("'", "", handRegex1)
handRegex3 = re.sub("/", "", handRegex2)
handRegex4 = re.sub(" suited", "s", handRegex3)
handRegex5 = re.sub(" unsuited", "o", handRegex4)
handRegex6 = re.sub("""
""", " ", handRegex5)
handRegex7 = re.sub("\n", " ", handRegex6)
handRegex8 = re.sub("\s\s\s", ",", handRegex7)
separate = handRegex8.split(",")
print(handRegex7)
#using handRegex7 we can add each word to an individual cell. We have to separate the headers and sort those, the actual data should be easy to seperate by space charecter.
workbook = xlsxwriter.Workbook('/Users/colivart/Excel_Files/Texas_Hold_Em_6.xlsx')
worksheet = workbook.add_worksheet()
"""
We can use for loop to iterate through format variable.
This will allow us to add each hand
and it's values one by one.
"""
worksheet.write_column('A1', format)
workbook.close()
getContent()
【问题讨论】:
标签: python web-scraping