【问题标题】:How to web scrape all of the batters names?如何在网上刮掉所有击球手的名字?
【发布时间】:2018-09-20 03:07:26
【问题描述】:

我想收集 2018 年所有 MLB 击球手的统计数据。这是我目前的代码:

#import modules

from urllib.request import urlopen
from lxml import html

#fetch url/html

response = urlopen("https://www.baseball-reference.com/leagues/MLB/2018-standard-batting.shtml")
content = response.read()
tree = html.fromstring( content )

#parse data

comment_html = tree.xpath('//comment()[contains(., "players_standard_batting")]')[0]
comment_html = str(comment_html).replace("-->", "")
comment_html = comment_html.replace("<!--", "")
tree = html.fromstring( comment_html )
for batter_row in tree.xpath('//table[@id="players_standard_batting"]/tbody/tr[contains(@class, "full_table")]'):
    csk = batter_row.xpath('./td[@data-stat="player"]/@csk')[0]

当我刮掉所有的击球手时,每个名字都附加了 0.01。我尝试使用以下代码删除附加的数字:

bat_data = [csk]
string = '0.01'
result = []

for x in bat_data :
    if string in x:
        substring = x.replace(string,'')
        if substring != "":
            result.append(substring)
    else:
        result.append(x)
print(result)

此代码删除了数字,但是只打印了姓氏:

输出:

['Zunino, Mike']

此外,名称周围有括号和引号。名字也是倒序的。

1) 如何打印所有击球手的姓名?

2) 如何去掉引号和括号?

3) 我可以颠倒姓名的顺序,先打印名字然后再打印姓氏吗?

我希望的最终输出将是所有击球手的名字,如下所示:Mike Zunino。

我是这个网站的新手...我也是抓取/编码的新手,我将非常感谢我能获得的任何帮助! =)

【问题讨论】:

    标签: python xpath web-scraping lxml


    【解决方案1】:

    你可以用不同的方式做同样的事情。这是一种不需要后处理的方法。你得到你想要的名字:

    from urllib.request import urlopen
    from lxml.html import fromstring
    
    url = "https://www.baseball-reference.com/leagues/MLB/2018-standard-batting.shtml"
    
    content = str(urlopen(url).read())
    comment = content.replace("-->","").replace("<!--","")
    tree = fromstring(comment)
    for batter_row in tree.xpath('//table[contains(@class,"stats_table")]//tr[contains(@class,"full_table")]'):
        csk = batter_row.xpath('.//td[@data-stat="player"]/a')[0].text
        print(csk)
    

    你可能会得到如下输出:

    Jose Abreu
    Ronald Acuna
    Jason Adam
    Willy Adames
    Austin L. Adams
    

    【讨论】:

    • 这正是我想要的。您应该得到的不仅仅是一个复选标记......谢谢您,先生! =)
    • 再次感谢@SIM!如果我能再麻烦您一个问题,先生...如果我有 2 个不同的类别要抓取 - 例如 csk1 和 csk2 - 我如何使用 pandas 将两者保存到数据框中,以便我可以导出到 excel?跨度>
    • 对不起@Able Archer,我对数据框的了解几乎为零,所以我无法帮助你。
    • 完全不用担心@SIM...你对我的学习帮助很大!为此,我感谢你 =)
    【解决方案2】:

    您只会得到最后一个连击,因为您在第一个循环中每次都覆盖 csk 的值。首先初始化空列表bat_data,然后将每个batter添加到它。

    bat_data= []
    for batter_row in blah:
        csk = blah
        bat_data.append(csk)
    

    这将为您提供所有击球手的列表,['Abreu,Jose0.01', 'Acuna,Ronald0.01', 'Adam,Jason0.01', ...]

    然后循环遍历此列表,但您不必检查 string 是否在名称中。只需执行x.replace('0.01', ''),然后检查字符串是否为空。

    颠倒名字的顺序

    substring = substring.split(',')
    substring.reverse()
    nn = " ".join(substring)
    

    然后将 nn 附加到结果中。

    您得到引号和括号是因为您正在打印列表。而是遍历列表并打印每个项目。

    假设您正确获取了 bat_data,您的代码已编辑:

    for x in bat_data :
        substring = x.replace(string,'')
        if substring != "":
            substring = substring.split(',')
            substring.reverse()
            substring = ' '.join(substring)
            result.append(substring)
    
    for x in result:
        print(x)
    

    【讨论】:

    • 非常感谢@RajeshM!有什么方法可以向我展示完整的代码或更新我的代码?我不确定在哪里进行调整。我尝试以几种不同的方式运行代码,但遇到了一些问题。我确定这是我做错了。
    • 我之前的代码有问题。检查上面的更新代码。
    • 谢谢!我会对此进行研究并尝试从中学习。我会在不久的将来回复你。感谢您在忙碌的一天中抽出时间。真的很感激,先生。 =)
    【解决方案3】:

    1) 打印所有击球手姓名

    print(result)
    

    这将打印结果对象中的所有内容。如果它没有打印出您所期望的内容,那么还有其他问题。

    2) 删除引号 括号是因为它是一个数组对象。试试这个...

    print(result[0])
    

    这将告诉解释器在 0 索引处打印结果。

    3) 名称倒序

    试试

    name = result[0].split(“ “).reverse()[::-1]
    

    【讨论】:

    • 感谢您的回复 =) 我收到此错误 @Kenpachi: Traceback (最近一次通话最后一次): 文件 "C:\Users\xboss\Desktop\Pitchers in progress.py",第 37 行,在 name = result[0].split(" ").reverse().join() AttributeError: 'NoneType' object has no attribute 'join'
    • 我刚刚编辑了我的反转解决方案,这次我在 python 中对其进行了测试,这将按正确的顺序打印出名称!
    • Ty @Kenpachi!!非常感谢您的宝贵时间!
    • 没问题。乐于助人!
    猜你喜欢
    • 2019-01-18
    • 2021-02-05
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多