![](/img/trans.png)
[英]How to maintain case-sensitive tags in BeautifulSoup.BeautifulStoneSoup?
[英]Parsing w/ case-sensitive text/tags
我正在使用beautifulsoup解析文本,并希望返回父标记下方/下方的标记。 但是,在三个不同的文档之间,“所需数据集”的大写方式之间存在不一致。 见下文:
<td class="pl "...-unimportant bits of script here-...;>Desired Data Set...</td>
和
<td class="pl "...-unimportant bits of script here-...;>Desired data set...</td>
和
<td class="pl "...-unimportant bits of script here-...;>desired data set...</td>
到目前为止,这是我的代码:
import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(data.text, 'lxml')
filenames = ['Desired Data Set','desired data set','Desired data set']
for filename in filenames:
for item in soup.select('filename:contains("' + filename + '")'):
for td in item.find('td', text=filename).parent.find_all('td'):
data = [td.text.strip()]
print(data)
......它有效。
然而,当我开始使用更大的数据集时,我确信会出现更多的不一致,即使上述方法有效,它也是“hacky”,并且效率低或不够谨慎。 我想对所有需要的数据集使用一个文件名。
我试图使用lower()降低整个汤,但它会抛出NoneType错误。
您可以使用find_all()
方法的string
参数:
from bs4 import BeautifulSoup
data = '''<table><tr><td class="pl ">Desired Data Set...</td>
<td class="pl ">Desired data set...</td>
<td class="pl ">desired data set...</td>
<td class="pl ">Something else</td>
</tr></table>
'''
soup = BeautifulSoup(data, 'lxml')
for td in soup.find_all('td', string=lambda t: 'desired data set' in t.lower()):
print(td)
打印:
<td class="pl">Desired Data Set...</td>
<td class="pl">Desired data set...</td>
<td class="pl">desired data set...</td>
soup = BeautifulSoup(data.text.lower(), 'lxml')
可能是解决问题的“hacky”方式,但对于我的具体示例,它有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.