python - 使用 BeautifulSoup 使用下拉列表刮取表格内容
问题描述
我想从https://www.cbssports.com/nfl/playersearch?POSITION=RB&print_rows=9999为所有位置的所有玩家 抓取所有搜索结果。
我已经使用以下代码获得了所有 RB 玩家:
from bs4 import BeautifulSoup
import requests
html_text = requests.get('https://www.cbssports.com/nfl/playersearch?POSITION=RB&print_rows=9999')
html = html_text.text
soup = BeautifulSoup(html, 'html.parser')
player_table = soup.find('table', class_='data')
for tr in all_player_table.find_all('tr', class_=['row1','row2']):
tds = tr.find_all('td')
print(("Player:%s , Position:%s , Team: %s") % (tds[0].text, tds[1].text, tds[2].text))
我现在正面临着从下拉列表中抓取其他位置的玩家。最好的方法是什么?
解决方案
这个想法很简单:你可以抓取所有位置,修改 URL 并搜索所有玩家。在代码中:
from bs4 import BeautifulSoup
import requests
main_url = "https://www.cbssports.com/nfl/playersearch"
soup = BeautifulSoup(requests.get(main_url).text, "html.parser")
# Scrape all positions
positions = [o["value"] for o in soup.find("select", {'name' : "POSITION"}).find_all("option")]
for position in positions:
url = f"{main_url}?POSITION={position}&print_rows=9999"
# Find all players
soup = BeautifulSoup(requests.get(url).text, "html.parser")
for tr in soup.find("table", class_="data").find_all("tr", class_=["row1", "row2"]):
tds = tr.find_all('td')
print(("Player: %s , Position: %s , Team: %s") % (tds[0].text, tds[1].text, tds[2].text))
推荐阅读
- arrays - 如何在 Kotlin 中制作未经修改的 ByteArray
- r - 根据同一数据框中另一列的值计算或求和 2 列的值
- solr - 通过将索引目录复制到新的空集合来将独立的 Solr 迁移到 Solr Cloud
- php - 使用 exec 创建文件夹后压缩文件夹会导致没有文件夹创建和压缩失败
- java - 无法在 Wowza GoCoder 的 PlayerActivity 中播放视频
- terraform - MODULE 中的 Terraform 条件源
- javascript - 如何在网页上显示数据库中的内容并允许用户选择以获取更多信息
- gitlab - gitlab:我如何以编程方式下载 CI 管道末端发布的工件
- c# - 在 Excel 工作表/单元格中嵌入文件
- docker - Visual Studio Docker 工具 - 图像在哪里以及容器在哪里运行