【发布时间】:2018-07-17 05:58:46
【问题描述】:
我正在使用此代码查看一个 p 标签列表,该列表比我的示例中包含 1 个或多个 span 标签的要长得多。我知道列表中的 span 标签也有 font-style 属性。我一直试图弄清楚我正在查看的字体样式属性的特定跨度标记是否具有斜体值。如果字体样式是斜体,有没有办法获取字体样式属性的值或返回布尔值?
content = "<p dir="ltr">
<span style="color: rgb(0, 0, 0); font-style: normal; background-color: transparent; font-weight: 400; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">a</span>
</p>,
<p dir="ltr">
<span style="color: rgb(0, 0, 0); font-style: italic; background-color: transparent; font-weight: 400; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">b</span>
<span style="color: rgb(0, 0, 0); font-style: normal; background-color: transparent; font-weight: 400; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">c</span>
</p>,
<p dir="ltr">
<span style="color: rgb(0, 0, 0); font-style: normal; background-color: transparent; font-weight: 400; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">d</span>
<span style="color: rgb(0, 0, 0); font-style: italic; background-color: transparent; font-weight: 400; font-variant: normal; text-decoration: none; vertical-align: baseline; white-space: pre-wrap">e</span>
</p>"
soup = BeautifulSoup(test, 'html.parser')
page = {}
ital = []
i = 1
p = 1
for par in soup:
page[i] = {}
for x in par.find_all('span'):
if x['font-style'] == 'italic': #stuck here trying to figure out if font-style value is italic or not
ital.append(p)
par = 'par_{}'.format(p)
page[i].update({par:x.next})
p += 1
page[i].update({'ital':ital})
ital = []
i += 1
p = 1
更新:
我的目标是在page 上按顺序获取 span 标签之间的所有内容,并知道内容的哪一部分是斜体。
运行后这个页面应该是这样的
print(page)
{
1: {'ital': [],
'par_1':'a'},
2: {'ital': [1],
'par_1':'b',
'par_2':'c'},
3: {'ital': [2],
'par_1':'d',
'par_2':'e'}
}
当前此代码打印
print(page)
{
1: {'ital': [],
'par_1':'a'},
2: {'ital': [],
'par_1':'b',
'par_2':'c'},
3: {'ital': [],
'par_1':'d',
'par_2':'e'}
}
【问题讨论】:
-
风格真的是
italize吗?因为这既不是标准的 CSS 字体样式,也不是英文单词。 -
不,当我进入票证并且没有拼写检查时,我压力太大了。我会解决的
标签: python html python-3.x beautifulsoup python-requests