只获取带有BeautifulSoup的URL列表的第一个链接

时间:2012-10-14 14:54:18

标签: python parsing url beautifulsoup

我解析了一个完整的HTML文件,用Python中的Beautifulsoup模块提取了一些URL,代码很和平:

for link in soup.find_all('a'):
    for line in link :
        if "condition" in line :

           print link.get("href")

我在shell中获得了一系列观察if循环中条件的链接:

  • http:// ..link1
  • http:// ..link2
  • http:// ..linkn

如何才能将变量“输出”仅放入此列表的第一个链接?

修改

网页为:http://download.cyanogenmod.com/?device=p970,脚本必须在HTML页面中返回第一个短网址(http://get.cm / ...)。

2 个答案:

答案 0 :(得分:6)

你可以使用oneliner:

import re

soup.find('a', href=re.compile('^http://get.cm/get'))['href']

将其分配给变量:

variable=soup.find('a', href=re.compile('^http://get.cm/get'))['href']

我不知道你到底在做什么,所以我将从头开始发布完整的代码: NB!如果你使用bs4更改导入

import urllib2
from BeautifulSoup import BeautifulSoup
import re

request = urllib2.Request("http://download.cyanogenmod.com/?device=p970")
response = urllib2.urlopen(request)
soup = BeautifulSoup(response)
variable=soup.find('a', href=re.compile('^http://get.cm/get'))['href']
print variable

>>> 
http://get.cm/get/4jj

答案 1 :(得分:1)

您可以在BeautifulSoup中更轻松,更清晰地完成此操作,无需循环。

假设您解析的BeautifulSoup对象名为soup

output = soup.find(lambda tag: tag.name=='a' and "condition" in tag).attrs['href']
print output

请注意,find方法仅返回第一个结果,而find_all则返回所有结果。