为了账号安全,请及时绑定邮箱和手机立即绑定

如何选择具有特定属性类型的标签

如何选择具有特定属性类型的标签

婷婷同学_ 2022-05-24 13:15:20
这是事情我只想在其他乱七八糟的html中抓取这些标签<table bgcolor="FFFFFF" border="0" cellpadding="5" cellspacing="0" align="center">    <tr>        <td>            <a href="./index.html?id=subjective&page=2">                <img src='https://www.dogdrip.net/?module=file&act=procFileDownload&file_srl=224868098&sid=cc8c0afbb679bef6420500988a756054&module_srl=78' style='max-width:180px;max-height:270px' align='absmiddle' title="cutie cat">            </a>        </td>    </tr></table>我第一次尝试使用 CSS 选择器选择器是#div_article_contents > tr:nth-child(1) > th:nth-child(1) > table > tbody > tr:nth-child(1) > td > table > tbody > tr > td > a > img但soup.select('selector')没有奏效。它输出空列表。我不知道为什么其次,我尝试使用标签,每个我想抓取的东西都有特定的样式,所以我尝试了:soup.select('img[style = fixedstyle]')但它不起作用。这将是语法错误...我想要抓取的只是 href 链接列表和 img 标题列表请帮我
查看完整描述

1 回答

?
偶然的你

TA贡献1841条经验 获得超3个赞

如果img标签具有特定的样式值,您可以使用您尝试的内容,只需删除多余的空格:


from bs4 import BeautifulSoup


html='''

<a href='link'>

    <img src='address' style='max-width:222px;max-height:222px' title='owntitle'>

</a>

<a href='link'>

    <img src='address1' style='max-width:222px;max-height:222px' title='owntitle1'>

</a>

<a href='link'>

    <img src='address2' style='max-width:222px;max-height:222px' title='owntitle2'>

</a>

'''


srcs=[]

titles=[]

soup=BeautifulSoup(html,'html.parser')

for img in soup.select('img["style=max-width:222px;max-height:222px"]'):

    srcs.append(img['src'])

    titles.append(img['title'])

print(srcs)

print(titles)

否则,您可以从a标签开始,然后img像这样:


for a in soup.select('a'):

    srcs.append(a.select_one('img')['src'])

    titles.append(a.select_one('img')['title'])

print(srcs)

print(titles)


查看完整回答
反对 回复 2022-05-24
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号