1
我想從this網頁抓取數據,如位置和玩家的名字。我的代碼如下。不能只使用BS4從表中拉出可見的文本
#create url for the wikipedia data we are going to scrape
wikiURL = "https://en.wikipedia.org/wiki/2012_NFL_Draft"
#create array to store player info in
teams_players = []
# request and parse wikiURL
r = requests.get(wikiURL)
soup = BeautifulSoup(r.content, "html.parser")
#find table in wikipedia
playerData = soup.find('table', {"class": "wikitable sortable"})
for row in playerData.find_all('tr')[1:]:
cols = row.find_all(['td', 'th'])
if len(cols) < 6:
continue
teams_players.append((cols[5].text.strip(), cols[4].text.strip()))
for team, player in teams_players:
print('{:35} {}'.format(team, player))
的問題是,有一個與文本和在名稱字段中顯示的文本是「排序關鍵字」 span標記,所以輸出最終被加倍,並且顯示了象徵。
QB Luck, AndrewAndrew Luck †
QB Griffin III, RobertRobert Griffin III †
我試圖尋找{「類」:「FN」}但這只是返回空括號的列表。
我該如何才能拉出顯示的文字並忽略符號呢?
當我嘗試運行此代碼,我得到一個語法錯誤: print name_tag.text,name_tag.find_next(「td」)。a.text ^ SyntaxError:invalid syntax'我正在運行Python 3.5.2 – Michael
@Michael,根據運行的示例代碼使用parens –
這樣做。如果我要從數據中提取更多列,是否可以通過查找下一個或找到前一個「td」來完成?如果不是,那麼做到這一點的最好方法是什麼? – Michael