[英]How to select tags that have certain attribute type
这是东西
我只想在其他凌乱的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标题列表
请帮我
如果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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.