我正在為一個資料科學專案抓取棒球參考資料,并且在嘗試從特定聯賽中抓取球員資料時遇到了一個問題。一個本賽季開始打球的聯賽。當我抓取已經完成比賽的舊聯賽時,我沒有任何問題。但我想通過這個鏈接來了解聯盟:https ://www.baseball-reference.com/register/league.cgi?id= c346199a 隨著賽季的進行。然而,鏈接隱藏在許多看似純文本的內容后面。所以 BeautifulSoup.find_all('a', href = True) 不起作用。
因此,這就是我迄今為止的思考程序。
html = BeautifulSoup(requests.get('https://www.baseball-reference.com/register/league.cgi?id=c346199a').text, features = 'html.parser').find_all('div')
ind = [str(div) for div in html][0]
orig_ind = ind[ind.find('/register/team.cgi?id='):]
count = orig_ind.count('/register/team.cgi?id=')
team_links = []
for i in range(count):
# rn finds the same one over and over
link = orig_ind[orig_ind.find('/register/team.cgi?id='):orig_ind.find('title')].strip().replace('"', '')
# try to remove it from orig_ind and do the next link...
# this is the part that is not working rn
orig_ind = orig_ind.replace(link, '')
team_links.append('https://baseball-reference.com' link)
哪個輸出:
['https://baseball-reference.com/register/team.cgi?id=71fe19cd',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
'https://baseball-reference.com',
等等。我正在嘗試從此頁面獲取所有團隊鏈接:https ://www.baseball-reference.com/register/league.cgi?id=c346199a
然后爬到每個頁面上的播放器鏈接并收集一些資料。就像我說的那樣,它幾乎適用于我嘗試過的每一個聯賽,除了這個。
非常感謝任何幫助。
uj5u.com熱心網友回復:
您在此站點上看到的表格存盤在 HTML 注釋 ( <!-- ... -->) 中,因此 BeautifulSoup 通常看不到它們。要決議它們,請嘗試下一個示例:
import requests
from bs4 import BeautifulSoup, Comment
soup = BeautifulSoup(
requests.get(
"https://www.baseball-reference.com/register/league.cgi?id=c346199a"
).text,
features="html.parser",
)
s = "".join(c for c in soup.find_all(text=Comment) if "table_container" in c)
soup = BeautifulSoup(s, "html.parser")
for a in soup.select('[href*="/register/team.cgi?id="]'):
print("{:<30} {}".format(a.text, a["href"]))
印刷:
Battle Creek Bombers /register/team.cgi?id=f3c4b615
Kenosha Kingfish /register/team.cgi?id=71fe19cd
Kokomo Jackrabbits /register/team.cgi?id=8f1a41fc
Rockford Rivets /register/team.cgi?id=9f4fe2ef
Traverse City Pit Spitters /register/team.cgi?id=7bc8d111
Kalamazoo Growlers /register/team.cgi?id=9995d2a1
Fond du Lac Dock Spiders /register/team.cgi?id=02911efc
...and so on.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/486871.html
