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

Gab*_*ori 3 python url parsing beautifulsoup

我解析了整个HTML文件,使用Python中的Beautifulsoup模块提取了一些URL,并且代码安静:

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

           print link.get("href")
Run Code Online (Sandbox Code Playgroud)

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

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

我怎么能把变量"输出"只放在这个列表的第一个链接?

编辑:

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

roo*_*oot 6

你可以使用oneliner来做到这一点:

import re

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

将它分配给一个变量:

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

我不知道你究竟在做什么,所以我将从头开始发布完整的代码: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
Run Code Online (Sandbox Code Playgroud)