首页 > 解决方案 > 使用列表检索字符串值

问题描述

我在尝试在这里操作一些字符串时遇到了一些问题。我正在从网站上抓取一些数据,我面临两个挑战:

  1. 我正在抓取不必要的数据,因为我的目标网站有多余的类命名。我的目标是隔离这些数据并将其删除,这样我就可以只保留我感兴趣的数据。

  2. 保留数据后,我需要拆分字符串以便将一些信息存储到特定变量中。

所以最初我打算使用一个简单的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

你能告诉我如何在这里进行吗?

标签: pythonpython-3.xstringlist

解决方案


这个怎么样 ?

它不是那么漂亮,但只要总是有一个 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']

推荐阅读