BeautifulSoup从查找中获取属性

时间:2015-03-16 14:53:58

标签: python beautifulsoup

我是python的新手所以首先抱歉,我想打印来自beautifulsoup的find()方法选择的href内容,但我不能这样做,我不知道为什么。我这样做了

from bs4 import BeautifulSoup
from requests import session

payload = {
    'btnSubmit': 'Login',
    'username': 'xxx',
    'password': 'xxx'
   }

 with session() as c:
     c.post('http://www.xxx.xxx/login.php', data=payload)
     request = c.get('http://www.xxx.xxx/xxxx')
     soup=BeautifulSoup(request.content)
     row_int=soup.find('td',attrs={'class' : 'rnr-cc rnr-bc rnr-icons'})
     print row_int['href']

但我有这个错误

Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
execfile ('C:\Users\Francesco\Desktop\prova.py')
File "C:\Users\Francesco\Desktop\prova.py", line 15, in <module>
print row_int['href']
File "C:\Python27\lib\site-packages\bs4\element.py", line 905, in __getitem__
return self.attrs[key]
KeyError: 'href'

row_int的内容是这样的:

[<a class="rnr-button-img" data-icon="view" href="xxxxxxx" id="viewLink12" name="viewLink12" title="Details"></a>, u' ']

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您需要从a代码中获取链接(td元素):

row = soup.find('td', attrs={'class': 'rnr-cc rnr-bc rnr-icons'})
a = row.find('a', href=True)
if a:
    print a['href']

或者,CSS selector

更短
for a in soup.select('td.rnr-cc.rnr-bc.rnr-icons a[href]'):
    print a['href']