我正在嘗試從https://www.baseball-reference.com/leagues/MLB/2019.shtml抓取 MLB 數據。在頁面上有幾個數據表,特別是我對擊球和投球統計感興趣。我可以成功地從擊球臺中提取數據并將其放入數據框中,但是當我嘗試從投球臺中提取數據時出現錯誤,即使格式基本相同:from bs4 import BeautifulSoupimport pandas as pdimport timeimport requestsfor year in range(2018, 2020): url = "https://www.baseball-reference.com/leagues/MLB/{}.shtml".format(year) headers = {'user-agent': "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.text, 'html.parser') batting_table = soup.find("div", attrs={"id": "div_teams_standard_batting"}) pitching_table = soup.find("div", attrs={"id": "div_teams_standard_pitching"})我 100% 確定 HTML 引用是正確的。batting_table 很好,但 pitching_table 是“NoneType”。我知道有些問題可能是由于 html 頁面本身的結構造成的,但在這種情況下可能嗎?不確定這是否有用,但我在這些函數中使用這些表,我將要從每個團隊中提取的特定統計數據傳遞給這些表,然后將其放入列表中。這是我使用“find_all”并出現錯誤的地方:def batting_stats(bstat): tables = batting_table.find_all("td", attrs={"data-stat": bstat}) b_stats = [] for table in tables: b_stat = table.text b_stat = float(b_stat) b_stats.append(b_stat) b_stats = b_stats[:-2] #exclude total and average return b_statsdef pitching_stats(pstat): tables = pitching_table.find_all("td", attrs={"data-stat": pstat}) p_stats = [] for table in tables: p_stat = table.text p_stat = float(p_stat) p_stats.append(p_stat) p_stats = p_stats[:-2] return p_stats我希望這不僅僅是我忽略的一個小錯字,那將是非常令人沮喪的。謝謝大家的幫助,提前。編輯:所以感謝Dainius,我能夠找到解決方案!我沒有完全按照他們提供的鏈接中的建議做,但它幫助我意識到由于某種原因,投球臺在 HTML 中被評論,這在檢查網頁時并不明顯,所以我對 Dainius 的回復感到困惑.檢查顯示什么直到我真正打印了“湯”并最終看到它們的意思時,我才意識到。在快速搜索如何從 HTML 中提取注釋之后,解決方案只是添加了兩行代碼:comments = soup.find_all(text=lambda text: isinstance(text, Comment))pitching_html = comments[19]pitching_table = BeautifulSoup(pitching_html, 'lxml')
添加回答
舉報
0/150
提交
取消