【问题标题】:Beautiful Soup and Splinter - get href and src attributesBeautiful Soup and Splinter - 获取 href 和 src 属性
【发布时间】:2020-06-04 01:47:14
【问题描述】:

这是代码:

url = f'https://www.premierleague.com/players'

# Initiate a splinter instance of the URL
browser.visit(url)

browser.find_by_tag('div[class="table playerIndex"]')
soup = BeautifulSoup(browser.html, 'html.parser')
for el in soup:
    td =  el.findAll('td')
    for each_td in td:
        url = each_td.find('a', href=True)
        print (url)

命中目标项目,但后面跟着None

<a class="playerName" href="/players/19970/Max-Aarons/overview"><img alt="" class="img" data-player="p232980" data-script="pl_player-image" data-size="40x40" data-widget="player-image" src="//platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/Photo-Missing.png"/>Max Aarons</a>
None
None
<a class="playerName" href="/players/13279/Abdul-Rahman-Baba/overview"><img alt="" class="img" data-player="p118335" data-script="pl_player-image" data-size="40x40" data-widget="player-image" src="//platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/Photo-Missing.png"/>Abdul Rahman Baba</a>
None
None

如何获得hrefsrc 值?

【问题讨论】:

    标签: python beautifulsoup splinter


    【解决方案1】:

    您可以像字典一样访问元素的属性和属性。

    for el in soup: 
        td = el.findAll('td') 
        for each_td in td: 
            link = each_td.find('a', href=True)
            if link:
                print(link['href'])
            image = each_td.find('img')
            if image:
                print(image['src'])
    

    【讨论】:

    • 我已经试过了,作为一个字典。问题是if 条件,摆脱了None。谢谢
    • 另外,保留参数href=True 很重要,否则src 传递的是//platform-static-files.s3.amazonaws.com/premierleague/photos/players/40x40/Photo-Missing.png,而不是实际资源https://resources.premierleague.com/premierleague/photos/players/40x40/p232980.png
    • 乐于助人。我重新添加了href=True 参数。
    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 2017-08-14
    • 2018-06-29
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多