首页 > 解决方案 > 如何使用漂亮的汤和python获取特定的href url

问题描述

我正在尝试在此td标记中获取下载 URL

<a href="https://dibbs2.bsm.dla.mil/Downloads/Awards/18SEP19/GS07F5933RSPEFA519F0433.PDF" target="DIBBSDocuments" title="Link To Delivery Order Document"><img alt="PDF Document" border="0" height="16" hspace="2" src="https://www.dibbs.bsm.dla.mil/app_themes/images/icons/IconPdf.gif" width="16"/></a>, <a href="https://dibbs2.bsm.dla.mil/Downloads/Awards/18SEP19/GS07F5933RSPEFA519F0433.PDF" target="DIBBSDocuments" title="Link To Delivery Order Document">SPEFA519F0433</a>

上面的输出是由我的代码产生的:

downloandurl=batch.select("a[href*=https://dibbs2.bsm.dla.mil/Downloads/Awards/]")

如何从标签中获取href URL

我正在尝试检索这个

https://dibbs2.bsm.dla.mil/Downloads/Awards/18SEP19/GS07F5933RSPEFA519F0433.PDF

标签: pythonhtmlbeautifulsoup

解决方案


href从锚标签中获取值。

利用

  • 标签['hef']

或者

  • tag.get('href')

或者

  • tag.attrs.get('href')
from bs4 import BeautifulSoup
data='''<a href="https://dibbs2.bsm.dla.mil/Downloads/Awards/18SEP19/GS07F5933RSPEFA519F0433.PDF" target="DIBBSDocuments" title="Link To Delivery Order Document"><img alt="PDF Document" border="0" height="16" hspace="2" src="https://www.dibbs.bsm.dla.mil/app_themes/images/icons/IconPdf.gif" width="16"/></a>, <a href="https://dibbs2.bsm.dla.mil/Downloads/Awards/18SEP19/GS07F5933RSPEFA519F0433.PDF" target="DIBBSDocuments" title="Link To Delivery Order Document">SPEFA519F0433</a>'''
soup=BeautifulSoup(data,'html.parser')
for item in soup.select('a'):
    print(item['href'])
    print(item.get('href'))
    print(item.attrs.get('href'))


如果您关注一些特定的锚标记,则在查找标记中添加更多条件,例如。

for item in soup.select('a[target="DIBBSDocuments"]'):
    print(item['href'])
    print(item.get('href'))
    print(item.attrs.get('href'))

或以 href url 开头。

for item in soup.select('a[href^="https://dibbs2.bsm.dla.mil/Downloads/Awards"]'):
    print(item['href'])
    print(item.get('href'))
    print(item.attrs.get('href'))

推荐阅读