我解析了整个 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
我怎样才能仅将这个列表的第一个链接放入变量“输出”?
EDIT:
网页是:http://download.cyanogenmod.com/?device=p970,脚本必须返回 HTML 页面中的第一个短 URL (http://get.cm/...)。
你可以用 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']
我不知道你到底在做什么,所以我将从头开始发布完整的代码:
注意!如果您使用 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)