0

我试图从美丽汤中的 findAll 中排除某些结果。我正在尝试排除具有 media=print 属性的样式表链接

这是我的代码:

from bs4 import BeautifulSoup
import urllib2

url = "http://worldwildlife.org/"

request = urllib2.Request(url)
opener = urllib2.build_opener()
f = opener.open(request)

html = f.read()
soup = BeautifulSoup(html)
css_files = soup.findAll('link',{'rel':'stylesheet'})

print css_files

返回:

[<link href="/assets/application-b275a30a2c6726e3fabb10517f7cb812.css" media="all" rel="stylesheet" type="text/css"/>, <link href="/assets/print-f0ba9e9b867691bb2fea40b2ab4e78d7.css" media="print" rel="stylesheet" type="text/css"/>]

我尝试了各种方法,显然我对 python 很陌生,任何帮助将不胜感激。

4

1 回答 1

2

将您的搜索行修改为:

css_files = soup.findAll('link',{'rel':'stylesheet', 'media': lambda L: L != 'print'})
# [<link href="/assets/application-b275a30a2c6726e3fabb10517f7cb812.css" media="all" rel="stylesheet" type="text/css"/>]
于 2013-06-03T19:28:03.493 回答