我是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' ']
我哪里错了?
答案 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']