猿问

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

这是事情


我只想在其他乱七八糟的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 标题列表


请帮我


婷婷同学_
浏览 132回答 1
1回答

偶然的你

如果img标签具有特定的样式值,您可以使用您尝试的内容,只需删除多余的空格:from bs4 import BeautifulSouphtml='''<a href='link'>&nbsp; &nbsp; <img src='address' style='max-width:222px;max-height:222px' title='owntitle'></a><a href='link'>&nbsp; &nbsp; <img src='address1' style='max-width:222px;max-height:222px' title='owntitle1'></a><a href='link'>&nbsp; &nbsp; <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"]'):&nbsp; &nbsp; srcs.append(img['src'])&nbsp; &nbsp; titles.append(img['title'])print(srcs)print(titles)否则,您可以从a标签开始,然后img像这样:for a in soup.select('a'):&nbsp; &nbsp; srcs.append(a.select_one('img')['src'])&nbsp; &nbsp; titles.append(a.select_one('img')['title'])print(srcs)print(titles)
随时随地看视频慕课网APP

相关分类

Python
我要回答