0

我需要的数据存在于 2 种不同的组合下tag + class。我希望我的函数在这两种组合下进行搜索,并同时呈现这两种组合下的数据。这两种组合是互斥的。如果存在 1 个组合,则不存在其他组合。

我正在使用的代码是:

# -*- coding: cp1252 -*-
import csv
import urllib2
import sys
import urllib
import time
from bs4 import BeautifulSoup
from itertools import islice

def match_both2(arg1,arg2):
    if arg1 == 'div' and arg2 == 'DetailInternetFirstContent empty openPostIt':
        return True
    if arg1 == 'p' and arg2 == 'connection':
        return True
    return False


page = urllib2.urlopen('http://www.sfr.fr/mobile/offres/toutes-les-offres-sfr?vue=000029#sfrintid=V_nav_mob_offre-abo&sfrclicid=V_nav_mob_offre-abo').read()
soup = BeautifulSoup(page)

datas = soup.findAll(match_both2(0),{'class':match_both2(1)})
print datas

现在,我正在尝试使用match_both2函数来完成此操作,但它给了我TypeError,因为我只向它传递了 1 个参数,它需要 2 个。在这种情况下,我不知道如何将 2 个参数传递给它,通常我会调用这样的函数match_both2(example1,example2)。但是在这里,我想不出一种可以解决我的问题的方法。

请帮我解决这个问题。

4

1 回答 1

0

当您使用函数过滤匹配元素时,您传递的只是对函数的引用,而不是结果。换句话说,在它传递给.findAll().

该函数仅使用一个参数调用,即元素本身。此外,该class属性已被拆分为一个列表。因此,要匹配您的特定元素,您需要将匹配功能区分为:

def match_either(tag):
    if tag.name == 'div':
        # at *least* these three classes must be present
        return {'DetailInternetFirstContent', 'empty', 'openPostIt'}.issubset(tag.get('class', []))
    if tag.name == 'p':
        # at *least* this one class must be present
        return 'connection' in tag.get('class', [])

这个函数返回True一个p带有connection类的标签,或者一个div带有所有三个类的标签。

将其传递给findAll() 而不调用它

datas = soup.findAll(match_either)
于 2013-02-11T10:42:05.423 回答