[英]Beautifulsoup can't find tag by text
Beautifulsoup突然找不到它的文字标签。
我有一个html,其中出现此标记:
<span class="date">Telefon: <b>+421 902 808 344</b></span>
BS4找不到此标签:
telephone = soup.find('span',{'text':re.compile('.*Telefon.*')})
print telephone
>>> None
我尝试了很多方法
find('span',text='Telefon: ')
或find('span', text=re.compile('Telefon: .*')
但没有任何作用。 我已经尝试将html.parser
更改为lxml
。
可能有什么不对?
BeautifulSoup认为字符串Telefon:
作为span
标记内的bs4.element.NavigableString
。 所以你可以找到它
import bs4
import re
soup = bs4.BeautifulSoup('<span class="date">Telefon: <b>+421 902 808 344</b></span>')
for span in soup.find_all('span', {'class':"date"}):
if span.find(text=re.compile('Telefon:')):
for text in span.stripped_strings:
print(text)
# Telefon:
# +421 902 808 344
或者,您可以直接使用lxml:
import lxml.html as LH
root = LH.fromstring('<span class="date">Telefon: <b>+421 902 808 344</b></span>')
for span in root.xpath('//span[@class="date" and contains(text(), "Telefon:")]'):
print(span.text_content())
# Telefon: +421 902 808 344
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.