如何使用Python中的BeautifulSoup从href中提取部分文本

时间:2017-06-27 21:33:03

标签: python beautifulsoup

这是我的代码:

表示数据中的项目:

print(item.find_all('td')[2].find('a'))
print(item.find('span').text.strip())
print(item.find_all('td')[3].text)
print(item.find_all('td')[2].find(target="_blank").string.strip())

它在下面打印此文本。

<a href="argument_transcripts/2016/16-399_3f14.pdf" 
id="ctl00_ctl00_MainEditable_mainContent_rptTranscript_ctl01_hypFile" 
target="_blank">16-399. </a>

Perry v. Merit Systems Protection Bd.

04/17/17

16-399.

我想从href标签中得到的就是这部分:16-399_3f14

我该怎么做?感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用find_all来拉取具有href属性的锚元素,然后解析您要查找的信息的href值。

from BeautifulSoup import BeautifulSoup

html = '''<a href="argument_transcripts/2016/16-399_3f14.pdf" 
id="ctl00_ctl00_MainEditable_mainContent_rptTranscript_ctl01_hypFile" 
target="_blank">16-399. </a>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    url = a['href'].split('/')
    print url[-1]

这应输出您要查找的字符串。

16-399_3f14.pdf