2014-01-25 140 views
0

您好我需要一个变量传递给soup.find()函数,但它不工作:( 有谁知道一个解决方案?是否可以将一个变量传递给(Beautifulsoup)soup.find()?

from bs4 import BeautifulSoup 

html = '''<div> blabla 
<p class='findme'> p-tag content</p> 
</div>''' 

sources = {'source1': '\'p\', class_=\'findme\'', 
      'source2': '\'span\', class_=\'findme2\'', 
      'source1': '\'div\', class_=\'findme3\'',} 

test = BeautifulSoup(html) 

# this works 
#print(test.find('p', class_='findme')) 
# >>> <p class="findme"> p-tag content</p> 


# this doesn't work 
tag = '\'p\' class_=\'findme\'' 

# a source gets passed 
print(test.find(sources[source])) 
# >>> None 

我想它分裂为建议这样的:

pattern = '"p", {"class": "findme"}' 
tag = pattern.split(', ') 
tag1 = tag[0] 
filter = tag[1] 
date = test.find(tag1, filter) 

我不明白的错误,只是日期没有问题是propably TAG1的内容和过滤pycharm的debuger给我:

tag1 = '"p"' 
filter = '{"class": "findme"}' 

打印它们并不显示这些apostrophs。是否有可能删除这些apostrophs?

+0

不,变量将无法工作,因为这不是一个标签名.. –

回答

2

第一个参数是一个标签名称,而你的字符串不包含那个。 BeautifulSoup(或Python,通常)不会解析出这样的字符串,它不会猜测你在该值中放置了一些任意的Python语法。

分离出的成分:

tag = 'p' 
filter = {'class_': 'findme'} 
test.find(tag, **filter) 
+0

谢谢您的coomment。问题是我正在阅读变量形式的dicitonary(请参阅我的第一篇文章),所以这不起作用 – user3199535

+0

@ user3199535:并且不能以不同的方式构建该字典? –

+0

@ user3199535:您必须自己解析该字符串,否则请拉出类名称和标记。 –

0

好,我又知道了,谢谢。

dic_date = {'source1': 'p, class:findme', other sources ...} 

pattern = dic_date[source] 
tag = pattern.split(', ') 
if len(tag) is 2: 
    att = tag[1].split(':') # getting the attribute 
    att = {att[0]: att[1]} # building a dictionary for the attributes 
    date = soup.find(tag[0], att) 
else: 
    date = soup.find(tag[0]) # if there is only a tag without an attribute 

那么它看起来并不很不错,但它的工作:)

+0

为什么字符串呢? ''dic_date = {'source1':{'tag':'p',{'filter':{'class':'findme'}}}}'然后使用Martijn的方法...'pattern = dic_date ['source1' ]'和'date = soup.find(pattern ['tag'],** pattern.get('filter',{})'etc ... –

+0

嗨,谢谢您的回复。不明白你在做什么,你能给我一个提示吗?特别是这些**是什么,我找不到任何东西,链接或我可以搜索的东西也可以。 – user3199535