Python - 如何找到id为' value'的所有跨度的文本。用美丽的汤?

时间:2018-02-14 08:56:59

标签: python python-3.x beautifulsoup

我想获得具有'值'类的跨度的所有文本。

<小时/> 然后,我需要使用文本的前9个字符获取页面的在线ISSN。我不需要文字以&#34;(打印)&#34;结尾的文字。但我确实需要结束于&#34;(在线) 实施例

<span class="bold">ISSN: </span>
<span class="value">0890-037X (Print)</span>
<span class="value">1550-2740 (Online)</span>

<小时/> 在这里,我需要得到&#34; 1550-2740&#34;因为它是在线ISSN。 我想我需要找到所有的跨度,检查课程,然后检查文本。如果文字结束于&#34;(在线)&#34;然后我需要获得前9个字符。 我该怎么做呢? 提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用find_all提取元素。创建generator(或list,如果您愿意),这只是每个text属性。过滤掉那些不以"(Online)"结尾的内容并将其切片以仅提取ISBN。我使用generatornext()来获得第一次出现,但如果您想要所有这些(如果有多个),您可以使用列表。

希望这适用于整个文件!

soup = BeautifulSoup(open("p.html").read(), "lxml")
txt = (t.text for t in soup.find_all("span", class_="value"))
isbn = next(t[:9] for t in txt if t.endswith("(Online)"))

isbn设为'1550-2740'

答案 1 :(得分:1)

另一种方式可能如下所示:

soup = BeautifulSoup(content,"lxml")
for item in soup.find_all(class_="value"):
    if "Online" in item.text:
        print(item.text.split()[0])

输出:

1550-2740