【发布时间】:2019-01-09 14:50:01
【问题描述】:
<td style="vertical-align:bottom;background-color:#efefef;padding-left:2px;padding-top:2px;padding-bottom:2px;padding-right:2px;">
<div style="text-indent:26px;font-size:9pt;">
<font style="font-family:Helvetica,sans-serif;font-size:9pt;">
iPhone
</font>
<font style="font-family:Helvetica,sans-serif;font-size:9pt;">
<sup style="vertical-align:top;line-height:120%;font-size:pt">
(1)
</sup>
</font>
</div>
</td>
<td style="vertical-align:bottom;padding-left:2px;padding-top:2px;padding-bottom:2px;background-color:#efefef;">
<div style="text-align:left;font-size:9pt;">
<font style="font-family:Helvetica,sans-serif;font-size:9pt;">
$
</font>
</div>
</td>
<td style="vertical-align:bottom;background-color:#efefef;padding-top:2px;padding-bottom:2px;">
<div style="text-align:right;font-size:9pt;">
<font style="font-family:Helvetica,sans-serif;font-size:9pt;">
29,906
</font>
</div>
</td>
<td style="vertical-align:bottom;background-color:#efefef;">
<div style="text-align:left;font-size:10pt;">
<font style="font-family:inherit;font-size:10pt;">
<br/>
</font>
</div>
</td>
我正在尝试使用 lxml 来获取两个字段:iPhone 和 29,906。
这是一个更大的 html 文件的一部分。
我找到了如何提取每个 td 中的字体,但我需要能够匹配 iPhone 字段和 29,906 字段。
我能想到的一种方法是将所有内容放入一个非常长的数组中并搜索“iPhone”并返回 iPhone + 2 值,但这似乎非常冗长且效率低下。
谁能指导我正确的方向?
这是我目前所拥有的:
from bs4 import BeautifulSoup
import requests
from lxml import html, cssselect
link = "https://www.sec.gov/Archives/edgar/data/320193/000032019318000100/a10-qq320186302018.htm"
response = requests.get(link)
soup = BeautifulSoup(response.text, 'html.parser')
str_soup = str(soup)
doc = html.document_fromstring(str_soup)
for col in doc.cssselect('font'):
try:
style = col.attrib['style']
if style=="font-family:Helvetica,sans-serif;font-size:9pt;":
print(col.text.strip())
except:
pass
这会返回所有文本,但不是我需要的。
【问题讨论】:
标签: python html parsing beautifulsoup lxml