python - 使用列表检索字符串值
问题描述
我在尝试在这里操作一些字符串时遇到了一些问题。我正在从网站上抓取一些数据,我面临两个挑战:
我正在抓取不必要的数据,因为我的目标网站有多余的类命名。我的目标是隔离这些数据并将其删除,这样我就可以只保留我感兴趣的数据。
保留数据后,我需要拆分字符串以便将一些信息存储到特定变量中。
所以最初我打算使用一个简单的split()
函数并将每个新字符串存储到列表中,然后使用它来保留我想要的部分。不幸的是,每次我这样做时,我都会得到 3 个无法操作/拆分的单独列表。
这是代码:
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome('\\Users\\rapha\\Desktop\\10Milz\\4. Python\\Python final\\Scrape\\chromedriver.exe')
driver.get("https://www.atptour.com/en/scores/2020/7851/MS011/match-stats")
content = driver.page_source
soup = BeautifulSoup(content, "html.parser" )
for infos in soup.find_all('h3', class_='section-title'):
title = infos.get_text()
title = ' '.join(title.split())
title_list = []
title_list = title.split(" | ")
print(title_list)
这是“原始数据”检索
Player Results
Tournament Results
Salvatore Caruso VS. Brandon Nakashima | Indian Wells 2020
这就是我想要实现的目标
Variable_1 = Salvatore Caruso
Variable_2 = Brandon Nakashima
Variable 3 = Indian Wells
Variable 4 = 2020
你能告诉我如何在这里进行吗?
解决方案
这个怎么样 ?
它不是那么漂亮,但只要总是有一个 VS 就可以工作。和一个 | 分隔名称,并且年份的日期始终为 4 位数字。
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome('/home/lewis/Desktop/chromedriver')
driver.get("https://www.atptour.com/en/scores/2020/7851/MS011/match-stats")
content = driver.page_source
soup = BeautifulSoup(content, "html.parser" )
text = soup.find_all('h3', class_='section-title')[2].get_text().replace("\n","")
while text.find(" ")> -1:
text = text.replace(" "," ")
text = text.strip()
#split by two parameters
split = [st.split("|") for st in text.split("VS.")]
#flatten the nested lists
flat_list = [item for sublist in split for item in sublist]
#extract the date from the end of the last item
flat_list.append(flat_list[-1][-4:])
#remove date fromt the 3rd item
flat_list[2] = flat_list[2][:-4]
#strip any leading or trailing white space
final_list = [x.strip() for x in flat_list]
print(final_list)
输出
['Salvatore Caruso', 'Brandon Nakashima', 'Indian Wells', '2020']
推荐阅读
- cluster-analysis - 如何在 Goole Earth Engine 无监督分类中仅显示一个集群
- flutter - 如何在控制台中获取图像的参考高度或宽度
- mysql - Sequelize 不会为 findAll 和 findOne 方法中的无效输入抛出错误
- c - 为什么要在字符串末尾添加 1?在这段代码中
- reactjs - 如何在本机反应中创建滑动标签按钮
- python - 转置数据帧,除了一列时间戳
- xsd - 平面文件的架构
- json - 如何在 Eclipse 中包含 json - 库
- openapi - 使用“express-openapi-validator”时无法传递动态查询参数
- c# - 转换中文日期时间字符串会引发错误