使用BeautifulSoup查找名为data-stats的属性 - python

我目前正在研究网络抓取工具,这将使我能够从足球运动员那里获取统计数据。如果我能抓住div,通常这将是一件容易的事,但是,该网站使用名为data-stats的属性,并将其像一个类一样使用。这是一个例子。

<th scope="row" class="left " data-stat="year_id"><a href="/years/2000/">2000</a></th>

如果您想亲自检查该站点,请点击这里。

https://www.pro-football-reference.com/players/B/BradTo00.htm

我尝试了几种不同的方法。要么根本不起作用,要么我可以启动for循环并将其放入数组中,但是您会注意到,表中的所有内容都不都是相同的var类型。

对不起,格式和语法。

到目前为止,这是我所拥有的,我确定它不是看起来最好的代码,主要是我自己尝试过的代码,以及从Google搜索中混入的一些东西。忽略我尝试不同操作的随机导入

# import libraries
import csv
from datetime import datetime
import requests
from bs4 import BeautifulSoup
import lxml.html as lh
import pandas as pd

# specify url
url = 'https://www.pro-football-reference.com/players/B/BradTo00.htm'

# request html
page = requests.get(url)

# Parse html using BeautifulSoup, you can use a different parser like lxml if present
soup = BeautifulSoup(page.content, 'lxml')
# find searches the given tag (div) with given class attribute and returns the first match it finds



headers = [c.get_text() for c in soup.find(class_ = 'table_container').find_all('td')[0:31]]

data = [[cell.get_text(strip=True) for cell in row.find_all('td')[0:32]]
        for row in soup.find_all("tr", class_=True)]

tags = soup.find(data ='pos')
#stats = tags.find_all('td')

print(tags)

参考方案

不清楚您到底要提取什么,但这可能会有所帮助:

import requests
from bs4 import BeautifulSoup as bs

url = 'https://www.pro-football-reference.com/players/B/BradTo00.htm'

page = requests.get(url)
soup = bs(page.text, "html.parser")

# Extract table
table = soup.find_all('table')
# Let's extract data from each row in table
for row in table:
    col = row.find_all('td')
    for c in col:
        print(c.text)

希望这可以帮助!

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python:传递记录器是个好主意吗? - python

我的Web服务器的API日志如下:started started succeeded failed 那是同时收到的两个请求。很难说哪一个成功或失败。为了彼此分离请求,我为每个请求创建了一个随机数,并将其用作记录器的名称logger = logging.getLogger(random_number) 日志变成[111] started [222] start…

Python-Excel导出 - python

我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…