您好我需要一个变量传递给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?
不,变量将无法工作,因为这不是一个标签名.. –