【问题标题】:BeautifulSoup initialization type Error -- trouble troubleshootingBeautifulSoup 初始化类型错误——故障排查
【发布时间】:2021-01-04 20:45:15
【问题描述】:

错误指向这个line of the bs4 source code

我正在使用依赖于 BeautifulSoup 的第 3 方模块。我正在使用它单独创建 NBA 球员统计数据的 DataFrame,然后将它们连接起来以制作一个大型 DataFrame。下面代码中的列表比较适用于一些 DF,但随后出现 TypeError: object of type 'NoneType' has no len() 错误

相关代码:

import pandas as pd
from PandasBasketball.stats import player_stats

dfs = [player_stats(requests.get(url), "per_minute") for url in full_player_urls[600:]]
all_stats = pd.concat(dfs)
all_stats[::500]

我尝试过的事情:

  • 检查full_player_urls 是否正确生成。这是。它是一个 URL 列表,例如:http://www.basketball-reference.com/players/b/burrobo01.html
  • 已验证 player_stats() 对 URL 正常工作: player_stats(requests.get('http://www.basketball-reference.com/players/b/bustida01.html'), "per_minute") 以上正确地生成了从该网页上的表生成的 DataFrame。这正在按预期工作。

【问题讨论】:

  • 尝试调用.content 方法。 requests.get(url).content
  • @MendelG TY 回复。返回AttributeError: 'str' object has no attribute 'text'
  • 尝试设置网址“basketball-reference.com/leagues/NBA_2021_per_minute.html”。当我调试您的代码时,它找不到返回 bs4 对象的表。
  • 我认为有些url不包含tables元素,所以markup参数是None。
  • @liontass 它们都包含表格。您建议的网址不正确。

标签: python python-3.x pandas beautifulsoup


【解决方案1】:

我的猜测是站点服务器正在识别您在很短的时间内发出许多请求,并且在循环中的某个时刻阻止了您。你可以做几件事。最简单的就是在每次迭代之后放一点时间延迟。如果这不起作用,请告诉我,我们可以修复一下:

import pandas as pd
from PandasBasketball.stats import player_stats
import time
import random
import requests

dfs = []
for url in full_player_urls[600:]:     
    dfs.append(player_stats(requests.get(url), "per_minute"))
    x = random.uniform(0, 10) 
    time.sleep(x)
       
all_stats = pd.concat(dfs)
all_stats[::500]

【讨论】:

    猜你喜欢
    • 2020-11-23
    • 1970-01-01
    • 2012-02-01
    • 2023-03-17
    • 1970-01-01
    • 2015-01-13
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多