2013-03-09 73 views
0

我正在使用BeautifulSoup使用以下代码解析网站。我可以解析网站并打印数据,但是,我只想打印链接中的部分数据。任何人都可以提供关于如何做到这一点的投入?仅使用美丽的汤打印链接的特定部分

from bs4 import BeautifulSoup as bs 
import argparse 
import urllib 
import urllib2 
import getpass 
import re 
import requests 

def update (url): 
    print url 
    req = urllib2.Request(url=url) 
    try: 
     f = urllib2.urlopen(req) 
     txt = f.read() 
     soup = bs(txt) 
     print soup 
     f.close() 


def main(): 
    #For logging 
    print "test" 
    parser = argparse.ArgumentParser(description='This is the update.py script created by test') 
    parser.add_argument('-u','--url',action='store',dest='url',default=None,help='<Required> url link',required=True) 
    results = parser.parse_args()# collect cmd line args 
    url = results.url 
    #print url 
    update(url) 
if __name__ == '__main__': 
    main() 

以下是当前输出。预期结果如下所示。

current output :- 

==== Test results ==== 

results are in \\data\loc 

==== <font color="#008000">Build Combo</font> ==== 

{| border="1" cellspacing="1" cellpadding="1" 
|- 
! bgcolor="#67B0F9" scope="col" | test1 
! bgcolor="#67B0F9" scope="col" | test2 
! bgcolor="#67B0F9" scope="col" | test3 
! bgcolor="#67B0F9" scope="col" | test4 
|- 
| [http:link.com] 
|} 

==== <font color="#008000">COde:</font> ==== 

Expected output:- 

==== <font color="#008000">Build Combo</font> ==== 

{| border="1" cellspacing="1" cellpadding="1" 
|- 
! bgcolor="#67B0F9" scope="col" | test1 
! bgcolor="#67B0F9" scope="col" | test2 
! bgcolor="#67B0F9" scope="col" | test3 
! bgcolor="#67B0F9" scope="col" | test4 
|- 
| [http:link.com] 
|} 
+0

你最终解决了这个问题吗? – TankorSmash 2013-03-27 23:24:08

回答

0

我会是第一个承认我不太清楚你问什么,但我认为这是要只打印a元素,而不是整个soup如果我不是错误。如果是这种情况,你需要find你想要打印的元素,然后,打印出来。假设你正在寻找一个a元素,你的更新方法可能看起来更像这样。

def update (url): 
    print url 
    req = urllib2.Request(url=url) 
    try: 
     f = urllib2.urlopen(req) 
     txt = f.read() 

     soup = bs(txt) 
     a_element = soup.find("a") 
     print a_element 

    f.close()