【问题标题】:For loop with lot of different Urls具有许多不同 URL 的循环
【发布时间】:2022-01-26 02:40:36
【问题描述】:

在 python 中完全是新手,经过许多 youtube 视频和教程后,我试图从 flashscore 中获取篮球首发阵容。 这是一个链接示例:https://www.flashscore.it/partita/6PN3pAhq/#informazioni-partita/formazioni

正如您在中间看到的那样,有一个与特定匹配对应的代码 (6PN3pAhq):每场匹配都有不同的匹配,我抓取了所有结果(目前为 144 个匹配)并将其存储到一个 Excel 文件中。 ..但现在我正在寻找通过这些不同的 Urls 循环的最佳方法,以抓取每场比赛的阵容(并附加到唯一的数据框)...

这是我上面网址的代码,非常感谢任何帮助!

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)

【问题讨论】:

    标签: python selenium for-loop web-scraping


    【解决方案1】:

    感谢您的帮助,我无法让您的代码工作,但我明白了您的意思...我通过这种方式解决了:

    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)
    

    比附加代码的其他部分,效果很好!

    【讨论】:

    • 乐于助人。一件小事:在读取文件时,请确保稍后使用f.close() 关闭它们,最好是在您完成提取所需的任何内容之后立即关闭它们。或者在with 子句下阅读它们(甚至更好)。对于像这样的个人项目来说不是超级重要,但不妨随着你的进步去了解它!更多信息在这里cmdlinetips.com/2016/01/…
    • 谢谢,没想到!
    【解决方案2】:

    如果您需要将所有匹配项存储在 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
    

    有很多方法可以解决这个问题,但这个简单实现的核心思想是将提取和解析游戏代码的方式与获取游戏分数的方式分开。解析器应该将游戏代码存储到某个最终集合中,您可以循环访问,获取游戏分数的逻辑可以专注于提取单个游戏的分数。

    【讨论】:

    • 感谢 karan 回复了我的帖子,但显然提到了您的帮助!
    猜你喜欢
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多