我有一个图像列表。我想用它们来搜索和提取位于下面<p>

2024-04-18 18:11:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从网站上抓取图片的图片名列表,比如:

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>

Tags: srchttptargetimg图片widthtdgov
1条回答
网友
1楼 · 发布于 2024-04-18 18:11:40
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,我们希望文本‘联邦渔业部’与之相关。

我想那应该是一个dict之类的。但是,我试着用tag.parent.parent.next_sibling这样做,但不起作用,我会研究一下 稍后编辑并添加。你知道吗

相关问题 更多 >