您好我需要一個變量傳遞給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?
不,變量將無法工作,因爲這不是一個標籤名.. –