2014-09-12 54 views
-6

編輯我想用Python腳本來做到這一點: 更改鏈接的圖像鏈接,例:解析HTML文件不是與Python

<td>mylink.com</td> 

到:

<td><a href="mylink,com"><img src="myimage.jpg"></a></td> 

這個我試過用BeautifulSoup LIB:

soup = BeautifulSoup("<td>mylink.html</td>") 
soup.td.string.wrap(soup.new_tag("a")) 
text = soup.a.string 
soup.a.clear() 
soup.find('a')['href'] = text 
image = soup.new_tag('img') 
soup.a.append(image) 
soup.find('img')['src'] = "images/world_link.png" 

它工作正常,但我想添加另一個屬性target<a href="" target="",我該怎麼做?

現在我想通過所有TD循環,我想這:

from bs4 import BeautifulSoup 
soup = BeautifulSoup(open("C:\Users\Will\Desktop\htm.html")) 
td = soup.find_all('td') 
for s in td: 
    a = soup.new_tag("a", href=s.td.text, target='_blank') 
    img = soup.new_tag('img', src="images/world_link.png") 
    a.append(img) 
    s.td.string.replace_with(a) 

但是這麼想的工作,我有這樣的錯誤:AttributeError的:「NoneType」對象有沒有屬性「文本」

+3

什麼你試過了嗎?添加更多信息等。或者有人會提出問題並將被關閉。 – 2014-09-12 15:29:57

+2

沒有您請求軟件的網站。所以,我必須舉報。 – 2014-09-12 15:33:37

回答

-1

我發現soulution:

from bs4 import BeautifulSoup 
soup = BeautifulSoup(open("C:\Users\Will\Desktop\htm.html")) 
td = soup.find_all('td') 
for s in td: 
    a = soup.new_tag("a", href=s.text, target='_blank') 
    img = soup.new_tag('img', src="images/world_link.png") 
    a.append(img) 
    s.string.replace_with(a) 
+0

您找到了解決方案。究竟。恭喜。 – alecxe 2014-09-17 03:43:01

0

new_tag()接受屬性作爲關鍵字參數,通過target作爲其中之一。

另外,代替wrap()clear(),你可以用replace_with()達到同樣的效果更容易:

from bs4 import BeautifulSoup 


soup = BeautifulSoup("<td>mylink.html</td>") 
td = soup.td 

a = soup.new_tag("a", href=td.text, target='_blank') 
img = soup.new_tag('img', src="images/world_link.png") 
a.append(img) 

td.string.replace_with(a) 

print soup.prettify() 

打印:

<td> 
    <a href="mylink.html" target="_blank"> 
     <img src="images/world_link.png"/> 
    </a> 
</td>