【问题标题】:Incrementing over a URL variable在 URL 变量上递增
【发布时间】:2018-12-13 20:04:41
【问题描述】:
import urllib2

import pandas as pd
from bs4 import BeautifulSoup

x = 0
i = 1
data = []
while (i < 13):
    soup = BeautifulSoup(urllib2.urlopen(
        'http://games.espn.com/ffl/tools/projections?&slotCategoryId=4&scoringPeriodId=%d&seasonId=2018&startIndex=' % i, +str(x)).read(), 'html')
    tableStats = soup.find("table", ("class", "playerTableTable tableBody"))
    for row in tableStats.findAll('tr')[2:]:
        col = row.findAll('td')
        try:
            name = col[0].a.string.strip()
            opp = col[1].a.string.strip()
            rec = col[10].string.strip()
            yds = col[11].string.strip()
            dt = col[12].string.strip()
            pts = col[13].string.strip()
            data.append([name, opp, rec, yds, dt, pts])
        except Exception as e:
            pass
    df = pd.DataFrame(data=data, columns=[
                      'PLAYER', 'OPP', 'REC', 'YDS', 'TD', 'PTS'])
    df
    i += 1

我一直在与梦幻足球项目合作,我正在尝试增加所有星期的数据,以便我可以为每周的前 40 名球员创建一个数据框。

通过在网址的PeriodId 部分手动输入周数,我已经能够在我选择的任何一周获得它,但我试图以编程方式每周增加它以使其更容易。我曾尝试使用PeriodId='+ I +'PeriodId=%d,但我不断收到有关 str 和 int 连接和错误操作数的各种错误。有什么建议或提示吗?

【问题讨论】:

  • 您好 Jonathan,查看您遇到的具体错误以及正确构建的 URL 示例会有所帮助。在你的位置,我首先隔离构造我传递给 urllib2 的 URL 的代码,以检查正在生成的内容。

标签: arrays pandas dataframe beautifulsoup increment


【解决方案1】:

尝试删除%istr(x) 之间的逗号以连接字符串,看看是否有帮助。

soup = BeautifulSoup(urllib2.urlopen('http://games.espn.com/ffl/tools/projections?&amp;slotCategoryId=4&amp;scoringPeriodId=%d&amp;seasonId=2018&amp;startIndex='%i, +str(x)).read(), 'html')

应该是:

soup = BeautifulSoup(urllib2.urlopen('http://games.espn.com/ffl/tools/projections?&amp;slotCategoryId=4&amp;scoringPeriodId=%d&amp;seasonId=2018&amp;startIndex='%i +str(x)).read(), 'html')

【讨论】:

    【解决方案2】:

    如果您在连接或格式化 URL 时遇到问题,请创建变量而不是用 BeautifulSoupurllib2.urlopen 写一行。

    使用括号格式化多个值,例如"before %s is %s" % (1, 0)

    url = 'http://games.espn.com/ffl/tools/projections?&slotCategoryId=4&scoringPeriodId=%s&seasonId=2018&startIndex=%s' % (i, x)
    # or
    #url = 'http://games.espn.com/ffl/tools/projections?&slotCategoryId=4&scoringPeriodId=%s&seasonId=2018&startIndex=0' % i
    html = urllib2.urlopen(url).read()
    soup = BeautifulSoup(html, 'html.parser')
    

    使代码排序器不会影响性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多