2014-01-25 139 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