2015-03-02 42 views
0

我正在使用網絡抓取工具,它有許多不同的變量,因此將每個變量保存到一行對我來說很重要。目前的變量我的工作我都下到這一點:如何從一行中的<a>字符串中刪除鏈接?

<a href="http://website.com/example/123" target="_blank">Example</a> 

有沒有簡單的方法,我可以簡單地得到一個代碼行報廢了網站(http://website.com/example/123在這種情況下)?

我目前正在使用urllib,re和BeautifulSoup,所以任何這些庫都很好。我嘗試加入

.find('a', attrs={'href': re.compile("^http://")}) 

到我的行結束,但它使輸出沒有任何返回。

回答

2

我相信所有你需要做的就是yourVarName [ 'href' 屬性]:

from bs4 import BeautifulSoup 

html = '''<a href="http://website.com/example/123" target="_blank">Example</a>''' 

soup = BeautifulSoup(html) 

for a in soup.find_all('a', href=True): 
    print "Found the URL:", a['href'] 

找到的網址:http://website.com/example/123

https://stackoverflow.com/a/5815888/3920284

+0

我不能要求更好的答案,謝謝! – ArnoldM904 2015-03-03 00:13:58

+0

,或者'soup.select('a [href]')'。 – alecxe 2015-03-03 01:32:04