完全是 Python 新手,在觀看了許多 youtube 視頻和教程之后,我正試圖從 flashscore 中獲取籃球首發陣容。以下是鏈接示例:https : //www.flashscore.it/partita/6PN3pAhq/#informazioni-partita/formazioni
正如你在中間看到的,有一個代碼 (6PN3pAhq) 對應于一個特定的匹配:每一個匹配都有一個不同的,我抓取了所有的結果(目前 144 個匹配)并將它存盤到一個 excel 檔案中......但是現在我正在尋找最好的方法來回圈這些不同的 URL 來抓取每個匹配的陣容(并附加到一個獨特的資料框)......
這是我上面網址的代碼,非常感謝任何幫助!
from selenium import webdriver
from bs4 import BeautifulSoup
from time import sleep
import pandas as pd
URL = "https://www.flashscore.it/partita/6PN3pAhq/#informazioni-partita/formazioni"
driver = webdriver.Chrome(r"C:\chromedriver.exe")
driver.get(URL)
sleep(5)
driver.find_element_by_id('onetrust-accept-btn-handler').click()
soup = BeautifulSoup(driver.page_source, "html.parser")
start = []
id = soup.find(class_="section")
for id2 in id.find_all("a", {"class": "lf__participantName"}):
start.append(id2.get('href'))
df = pd.DataFrame(start)
print (df)
uj5u.com熱心網友回復:
如果您需要將所有匹配項存盤在某個 excel 檔案中,您可以使用任意數量的開源工具來決議 excel 檔案并提取匹配號(請參閱:http : //www.python-excel.org/了解可用選項)。
但是,如果可能,最簡單的方法是完全繞過 excel 并將它們全部存盤在某個text檔案中或存盤到您的 Python 程式本身中:
games = [
'6PN3pAhq'
'game2Code',
'game3Code'
# and more...
]
在您的核心代碼中,使用字串模板:
# The url_template below contains a `{}` space where we can put any value when we format the string
# see: https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method
_url_template = "https://www.flashscore.it/partita/{}/#informazioni-partita/formazioni"
for game_code in games:
# extract getting game score logic somewhere else
get_game_scores(game_code)
def get_game_scores(game_code):
formatted_url = _url_template.format(game_code)
# do the stuff you did above
有很多方法可以解決這個問題,但這個簡單實作的核心思想是將提取和決議游戲代碼的方式與獲取游戲分數的方式分開。決議器應該將游戲代碼存盤到某個最終集合中,您可以回圈遍歷,并且獲取游戲分數的邏輯可以專注于僅提取單個游戲的分數。
uj5u.com熱心網友回復:
感謝您的幫助,我無法使您的代碼作業,但我明白您的意思……我是這樣解決的:
f = open("G:\matchid.txt", "r")
for id in f:
matchid.append(id)
_url_template = "https://www.flashscore.it/partita/{}/#informazioni-
partita/formazioni"
for x in matchid:
formatted_url = _url_template.format(x)
print(formatted_url)
比附上代碼的另一部分,效果很好!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/394765.html
下一篇:將過濾器應用于資料后進行網路抓取
