如何在此页面上找到某些链接?

时间:2014-02-21 13:35:25

标签: python beautifulsoup

请帮助编写更短的脚本。

import urllib
import pprint

import requests
import bs4


def get_friend_links(url, userName, html):
    soup = bs4.BeautifulSoup(html)
    links = soup.find('div', {'id': 'friends_overview'})
    links2 = links.findAll('a', {'class': 'ipsUserPhotoLink'})
    friendLinks = []
    for el in links2:
        friendLink = el['href']
        friendLinks.append(friendLink)

    pprint.pprint(friendLinks)


url = 'http://forum.saransk.ru/user/20892-ujdyj/'
userName = url.split('/')[-2]
userName = userName.replace('-', '_')
html = urllib.request.urlopen(url).read().decode('utf-8')

friendLinks = get_friend_links(url, userName, html)

它可以工作,但是我使用了太久而且记录周期。这不好

1 个答案:

答案 0 :(得分:0)

理论上你可以在一行中完成:

friendLinks = [el['href'] for el in bs4.BeautifulSoup(html).find('div', {'id': 'friends_overview'}).findAll('a', {'class': 'ipsUserPhotoLink'})]

但这是一个漫长而难以理解的路线。基本上,太多了 在我看来,一个很好的中间立场就是用列表替换明确的for循环。理解:

friendLinks = [el['href'] for el in links2]

甚至:

friendLinks = [el['href'] for el in links.findAll('a', {'class': 'ipsUserPhotoLink'})]

但在我看来,除此之外的任何事情都是过度杀伤并降低了可读性。

相关问题