簡體   English   中英

如何在html標記內解析html並打印特定輸出

[英]python How can I parse html and print specific output inside html tag

#!/usr/bin/env python    
import requests, bs4

    res = requests.get('https://betaunityapi.webrootcloudav.com/Docs/APIDoc/APIReference')
    web_page = bs4.BeautifulSoup(res.text, "lxml")

    for d in web_page.findAll("div",{"class":"actionColumnText"}):
        print d

結果:

<div class="actionColumnText">
<a href="/Docs/APIDoc/Api/POST-api-console-gsm-gsmKey-sites-siteId-endpoints-reactivate">/service/api/console/gsm/{gsmKey}/sites/{siteId}/endpoints/reactivate</a>
</div>
<div class="actionColumnText">
Reactivates a list of endpoints, or all endpoints on a site.        </div>

我有興趣看到輸出只有最后一行( 重新激活端點列表,或站點上的所有端點 )刪除開始和結束。 href的行不感興趣

任何幫助是極大的贊賞。

在一個簡單的例子中,您可以獲得文本

for d in web_page.find_all("div", {"class": "actionColumnText"}):
    print(d.get_text())

或者,如果您只想找到單個元素,則可以按索引獲取最后一個匹配項:

d = web_page.find_all("div", {"class": "actionColumnText"})[-1]
print(d.get_text())

或者,你也可以找到div與特定類的元素不具備的a子元素:

def filter_divs(elm):
    return elm and elm.name == "div" and "actionColumnText" in elm.attrs and elm.a is None 

for d in web_page.find_all(fitler_divs):
    print(d.get_text())

或者,如果是單個元素:

web_page.find(fitler_divs).get_text()

你可以用CSS選擇器選擇最后一個:

var d = web_page.select("div.actionColmnText:last")
d.string()

如果此文本更改,您可以使用

#!/usr/bin/env python    
import requests, bs4

    res = requests.get('https://betaunityapi.webrootcloudav.com/Docs/APIDoc/APIReference')
    web_page = bs4.BeautifulSoup(res.text, "lxml")

    yourText = web_page.findAll("div",{"class":"actionColumnText"})[-1]
    yourText = yourText.split('  ')[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM