【问题标题】:Grab the parent id tag with beautiful soup?用漂亮的汤抓住父母的身份证?
【发布时间】:2014-07-11 13:19:19
【问题描述】:

我在一个网站上抓取了一堆链接并将它们打印到一个列表中,但为了使列表更具可读性,我需要抓取链接父标签,但我不知道该怎么做。

我从中抓取的页面看起来像这样

<div id=bunch_of_links_1>
<a href=link 1>
<a href=link 2>
<a href=link etc> 
</div>
<div id=another_bunch_of_links_1>
<a href=another_link 1>
<a href=another_link 2>
<a href=another_link etc> 
</div>

所有链接都以 javascript 开头,所以我使用它来获取链接

links = soup.findAll(href=re.compile("javascript"))

然后使用 for 循环将它们全部打印出来。我应该如何获取每个链接的 div id 并将其与链接一起打印

编辑 - 我不确定在哪里插入 [(l, l.parent.get('id')) for l in links]

这是我的代码

links = soup.findAll(href=re.compile("javascript"))

for link in links:
full_link = link.get('href')
names = link.contents[0]
print "+names+", "+full_link+"

我希望能够与其他人一起打印 ID 标签

编辑 2

我把它放在我的 for 循环中

 idtag = link.parent.get('id')

当我打印 idtag var 时它不会给我任何错误,它返回 none

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    BeautifulSoup 中的每个元素都有一个指向父元素的.parent 属性。在这里使用它:

    [(l, l.parent.get('id')) for l in links]
    

    演示:

    >>> from bs4 import BeautifulSoup
    >>> soup = BeautifulSoup('''\
    ... <div id=bunch_of_links_1>
    ... <a href=link 1>
    ... <a href=link 2>
    ... <a href=link etc> 
    ... </div>
    ... <div id=another_bunch_of_links_1>
    ... <a href=another_link 1>
    ... <a href=another_link 2>
    ... <a href=another_link etc> 
    ... </div>
    ... ''')
    >>> 
    >>> links = soup.find_all('a')
    >>> [(l, l.parent.get('id')) for l in links]
    [(<a href="link">
    </a>, 'bunch_of_links_1'), (<a href="link">
    </a>, 'bunch_of_links_1'), (<a etc="" href="link">
    </a>, 'bunch_of_links_1'), (<a href="another_link">
    </a>, 'another_bunch_of_links_1'), (<a href="another_link">
    </a>, 'another_bunch_of_links_1'), (<a etc="" href="another_link">
    </a>, 'another_bunch_of_links_1')]
    

    【讨论】:

    • @user3332151:您的帖子内容太少,无法对此发表评论。底线:您可以在标签对象上使用.parent 来获取父对象。如何在代码中使用它取决于您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 2013-11-25
    • 1970-01-01
    • 2015-11-19
    相关资源
    最近更新 更多