2013-11-26 83 views
0

我正在使用美丽的汤的网络刮刀。这里是我的功能:Python从HTML标记中使用美丽的汤提取数字

journalist_result = soup.find_all("h4",class_="slab") 
    if len(journalist_result)>0: 
     journalist_share = int(re.match(r'\d+', journalist_result[0].get_text()).group()) 
    else: 
     journalist_share=0 

基本上,我想要做的就是提取共享链接的记者人数。在这种情况下是221(参见下面的举例):

CASE1:

<h4 class="slab">221 journalists shared this link. 
     <a href="/pros">Join</a> or <a href="/account/login?next=/whosharedmylink/?url=http://www.cnn.com/">sign in</a> to Muck Rack to view their names.</h3> 

我的代码工作正常,在有记者股或如果URL没有找到的情况。 但是,在以下情况下,我的代码游:

CASE2:

<h4 class="slab" style="margin-bottom:5px"> 

     This link hasn't yet been shared by any journalists.<br /><a href="/pros">Learn about using Muck Rack Pro</a> to connect with journalists. 
</h4> 

这是因为在2的情况下,没有发现记者。而我得到的错误是:

回溯(最近通话最后一个): 文件 “muckrackscraper.py”,第65行,在 journalist_share = INT(re.match(R '\ D +',journalist_result [0 ] .get_text())。group()) AttributeError:'NoneType'对象没有属性'group'

THanks提前有任何帮助!

回答

1

看起来好像你误解了为什么你的代码失败了。在情况2中是而不是,但在情况1中没有从re.match检查返回值,然后尝试None的函数调用。

re.match documentation

Return None if the string does not match the pattern; note that this is different from a zero-length match.

所以你的模式不匹配无论是在journalist_result[0].get_text();尝试检查这个值,并添加一个检查None

+0

谢谢你的帮助! – Telenoobies

相关问题