Python BeautifulSoup抓取某个href链接并将其存储

Python BeautifulSoup抓取某个href链接并将其存储,python,beautifulsoup,Python,Beautifulsoup,这就是我正在使用的HTML,我希望存储的是注释 2014年9月17日星期三凌晨1:11 论坛: 线程: 我希望获取此href链接扩展: 答复: 3. 意见: 108 我可以在打印两个href链接的地方找到它,但我不知道这样做的效率有多高: cleanup = BeautifulSoup(s2.content) for links in cleanup.find_all("dd"): if links.find("a") != None: print (links.a['

这就是我正在使用的HTML,我希望存储的是注释

2014年9月17日星期三凌晨1:11 论坛: 线程: 我希望获取此href链接扩展: 答复: 3. 意见: 108 我可以在打印两个href链接的地方找到它,但我不知道这样做的效率有多高:

cleanup = BeautifulSoup(s2.content)

for links in cleanup.find_all("dd"):
    if links.find("a") != None:
        print (links.a['href'])
输出:

./viewforum.php?f=12
./viewtopic.php?f=12&t=201&hilit=yeah

但是如何存储第二行呢?有什么提示吗?

例如,如果您知道它的内容,您可以与href进行匹配

if 'viewtopic' in links.a['href']:
    results.append(links.a)

您可以通过以下链接获得主题链接:

这将匹配以下链接:

内部dd标签 在href属性中包含viewtopic.php 结果是一个仅包含匹配元素的列表:

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <dd>
...    Wed Sep 17, 2014 1:11 am
... </dd>
... <dd>
... </dd>
... <dd>
...    Forum:
...    <a href="./viewforum.php?f=12">
...       Minewind Chat
...    </a>
... </dd>
... <dd>
...    Thread:
...    # I wish to grab this href link extension:
...    <a href="./viewtopic.php?f=12&amp;t=201&amp;hilit=yeah"> 
...       1.8
...    </a>
... </dd>
... <dd>
...    Replies:
...    <strong>
...       3
...    </strong>
... </dd>
... <dd>
...    Views:
...    <strong>
...       108
...    </strong>
... </dd>
... ''')
>>> topic_links = soup.select('dd a[href*=viewtopic.php]')
>>> for link in topic_links:
...     print link['href']
... 
./viewtopic.php?f=12&t=201&hilit=yeah

“dd a[href*=viewtock.php]”到底在做什么?我知道它是在dd中选择href,但是[]和*在做什么?@Anthony:dd a在dd标记下面选择一个标记。[]部分接着关注一个属性,这里是href。*=表达式要求使用包含给定文本的href属性。因此,任何具有href属性且包含文本viewtopic.php的元素都是合格的。好的,谢谢,我对python有点陌生,所以*=有点让人困惑,我认为这是一个乘法和赋值运算符。
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''\
... <dd>
...    Wed Sep 17, 2014 1:11 am
... </dd>
... <dd>
... </dd>
... <dd>
...    Forum:
...    <a href="./viewforum.php?f=12">
...       Minewind Chat
...    </a>
... </dd>
... <dd>
...    Thread:
...    # I wish to grab this href link extension:
...    <a href="./viewtopic.php?f=12&amp;t=201&amp;hilit=yeah"> 
...       1.8
...    </a>
... </dd>
... <dd>
...    Replies:
...    <strong>
...       3
...    </strong>
... </dd>
... <dd>
...    Views:
...    <strong>
...       108
...    </strong>
... </dd>
... ''')
>>> topic_links = soup.select('dd a[href*=viewtopic.php]')
>>> for link in topic_links:
...     print link['href']
... 
./viewtopic.php?f=12&t=201&hilit=yeah