我有一个从网站上抓取图像的图像名称列表,例如:
image1.jpg
image2.jpg
image3.jph
我想将这些图像与下面html中以下<p>
中的文本相关联。 因此,在下面的示例中,我想将 image1.jpg 和 image2.jpg 与"联邦渔业部"相关联
我如何使用 xpath(或其他东西(来做到这一点?
<td>
<p align = "center">
<a href "http://imagessite.gov" target = "_blank">
<img src = "image1.jpg" width = "100" height = "60" alt = "description">
<img src = "image2.jpg" width = "100" height = "60" alt = "a purple ant">
</a>
</p>
<p align = "center">
<img src = "globe.gif">
<a href = "http://imagesite.gov" target = "blank"> The Federal Department of Fish</a>
</p>
</td>
a ='''<td>
<p align = "center">
<a href "http://imagessite.gov" target = "_blank">
<img src = "image1.jpg" width = "100" height = "60" alt = "description">
<img src = "image2.jpg" width = "100" height = "60" alt = "a purple ant">
</a>
</p>
<p align = "center">
<img src = "globe.gif">
<a href = "http://imagesite.gov" target = "blank"> The Federal Department of Fish</a>
</p>
</td>'''
我已经存储了您提供给我们的html,其余代码应该看起来像这样
soup = BeautifulSoup(a, 'lxml')
table = soup.findAll('img') #finds all img tags
for tag in table: # We loop through the mentioned
if tag['src'].endswith('.jpg'): # this will check if the value from src ends with .jpg
print(tag['src'])
至于协会部分,我想你的意思是这样的。我稍后会添加一部分。我认为,用户提出的问题是,例如,如果我们查找 image1.jpg我们希望文本"联邦渔业部"与之关联/相关。
我想那将是一个字典或其他东西。但是,我尝试这样做,例如tag.parent.parent.next_sibling
它不起作用,我会调查它稍后进行编辑和添加。