gpt4 book ai didi

python - BeautifulSoup 从 find 中获取属性

转载 作者:行者123 更新时间:2023-12-01 04:47:43 26 4
gpt4 key购买 nike

我对 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' ']

我哪里错了?

最佳答案

您需要从 td 标记内获取链接(a 元素):

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']

关于python - BeautifulSoup 从 find 中获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29079918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com