Python (漂亮的汤)在按钮标签中获取数据

Python (漂亮的汤)在按钮标签中获取数据,python,web-scraping,beautifulsoup,python-requests,Python,Web Scraping,Beautifulsoup,Python Requests,我试图在按钮标签内刮出一个ImageId,希望得到结果: "25511e1fd64e99acd991a22d6c2d6b6c". 当我尝试时: drawing_url = drawing_url.find_all('button', class_='inspectBut')['onclick'] 它不起作用。出错- TypeError: list indices must be integers or slices, not str 输入= for article in soup.fin

我试图在按钮标签内刮出一个ImageId,希望得到结果:

"25511e1fd64e99acd991a22d6c2d6b6c".
当我尝试时:

drawing_url = drawing_url.find_all('button', class_='inspectBut')['onclick'] 
它不起作用。出错-

TypeError: list indices must be integers or slices, not str
输入=

for article in soup.find_all('div', class_='dojoxGridRow'):
drawing_url = article.find('td', class_='dojoxGridCell', idx='3')
drawing_url = drawing_url.find_all('button', class_='inspectBut')
if drawing_url:
    for e in drawing_url:
        print(e)
输出=

    <button class="inspectBut" href="#" 
        onclick="window.open('getImg?imageId=25511e1fd64e99acd991a22d6c2d6b6c&amp;
                 timestamp=1552011572288','_blank', 'toolbar=0, 
                 menubar=0, modal=yes, scrollbars=1, resizable=1, 
                 height='+$(window).height()+', width='+$(window).width())" 
         title="Open Image" type="button">
    </button>
... 
...

... 
...

您应该搜索

button_list = soup.find_all('button', {'class': 'inspectBut'})
这将为您提供按钮数组,您可以稍后通过

 [button['getimg?imageid'] for button in button_list]
您仍然需要进行一些解析,但我希望这可以让您走上正确的轨道


这里的错误是,您需要搜索正确的属性
class
并查找正确的html标记,具有讽刺意味的是,
getimg?imageid

,您首先需要检查属性是否存在。
tag.attrs
返回当前标记中存在的属性列表

考虑以下代码

代码:

from bs4 import BeautifulSoup
a="""
<td>
<button class='hi' onclick="This Data">
<button class='hi' onclick="This Second">
</td>"""
soup = BeautifulSoup(a,'lxml')
print([btn['onclick'] for btn in soup.find_all('button',class_='hi') if 'onclick' in btn.attrs])
['This Data','This Second']
或者你可以简单地这样做

[btn['onclick'] for btn in soup.find_all('button', attrs={'class' : 'hi', 'onclick' : True})]
试试这个

import re

#for all the buttons
btn_onlclick_list = [a.get('onclick') for a in soup.find_all('button')]
for click in btn_onlclick_list:
     a = re.findall("imageId=(\w+)", click)[0]
     print(a)

我不是一个专家,但不应该是
[onclick]
['onclick']
对不起,我实际上键入了['onclick'],它给出了错误:drawing\u url=drawing\u url。find\u all('button',class='inspectBut')['onclick']类型错误:列表索引必须是整数或切片,不可能重复提供url/足够的源html有助于获得更高质量的答案和可能更快的解决方案。如果得到相同的错误,则类型错误:列表索引必须是整数或切片,而不是字符串。使用print([btn['onclick']表示汤中的btn。如果btn.attrs中的'onclick',则查找所有('button',class='inspectBut'))很漂亮!它起作用了!非常感谢你!!如何循环所有按钮?不知道如何获取所有按钮,打印(单击)仅显示第一个按钮。不允许将数组导入到re。你有什么想法吗?对于多个按钮:
[btn.get(“onclick”)对于汤中的btn.find_all('button')]
你能编辑你的代码来完成你的答案吗请,非常感谢@LucasK.C.L更新了。你的答案最有效,我测试过了,非常感谢。这应该是最好的答案。