2013-07-13 44 views
1

我有一個簡單的HTML文件,我想要轉換。根據類的標籤,我需要modifiy內容:我是否有「H1」或「P」或其他類的如何從元素中獲取名稱美麗的湯4已解析

<HTML> 
<HEAD> 
<TITLE>Eine einfache HTML-Datei</TITLE> 
<meta name="description" content="A simple HTML page for BS4"> 
<meta name="author" content="Uwe Ziegenhagen"> 
<meta charset="UTF-8"> 
</HEAD> 
<BODY> 

<H1>Hallo Welt</H1> 

<p>Ein kurzer Absatz mit ein wenig Text, der relativ nichtssagend ist.</p> 

<H1>Nochmal Hallo Welt!</H1> 

<p>Schon wieder ein kurzer Absatz mit ein wenig Text, der genauso nichtssagend ist wie der Absatz zuvor.</p> 

</BODY> 
</HTML> 

我如何可以順利通過BS4樹,做取決於某些修改標籤?我想我需要一些switch語句來決定每個元素如何處理它。

from bs4 import BeautifulSoup 

with open ("simple.html", "r") as htmlsource: 
    html=htmlsource.read() 

soup = BeautifulSoup(html) 

for item in soup.body: 
    print(item) 

回答

1

BeautifulSoup標籤的對象都有一個name屬性,它可以檢查。例如,下面是它通過增加在postwalk +適當的標籤名「與此完成」每個節點的字符串變換樹中的一個功能:

def walk(soup): 
    if hasattr(soup, "name"): 
     for child in soup.children: 
      walk(child) 
     soup.append("Done with this " + soup.name) 

NB。代表文本內容的NavigableString對象和代表註釋的對象不具有namechildren等屬性,因此,如果您像上面一樣走完整個樹,則需要檢查手中是否實際上有標籤(我是用上面的hasattr調用;我想你可以檢查類型是bs4.element.Tag)。

+0

注意。這意味着要在標籤元素上調用。如果在文檔上調用,它也會修改''及其子元素,''元素和整個文檔('BeautifulSoup'對象)。 –

0

試試這個代碼:

from bs4 import BeautifulSoup 
with open ("simple.html", "r") as htmlsource: 
    html=htmlsource.read() 

soup = BeautifulSoup(html) 

for item in soup.body: 
    print(item) 

# You will select all of elements in the HTML page 
elems = soup.findAll() 
for item in elems: 
    try: 
     # Check if the class element is equal to a specified class 
     if 'myClass' == item['class'][0]: 
     print(item) 

    # Check if the tagname element is equal to a specified tagname 
    elif 'p' == item.name: 
     print(item) 

    except KeyError: 
    pass 
+0

我想這是行不通的。我需要的是一些代碼,它允許我瀏覽樹,並在每個元素上決定使用switch語句做什麼。例如:如果下一個元素是h1,則將其內容以粗體顯示,如果是段落,則以斜體印刷,等等...... –