使用bs4从href提取文本的一部分

时间:2018-09-11 04:46:11

标签: python beautifulsoup

想从href提取文本,看来我可以从HTML提取整个href

from bs4 import BeautifulSoup

soup=BeautifulSoup("""<div class="cdAllIn"><a href="/footba/all.aspx?lang=EN&amp;tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0" title="All Odds"><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div>
<div class="cdAllIn"><a href="/footba/all.aspx?lang=EN&amp;tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0" title="All Odds"><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div>
<div class="cdAllIn"><a href="/footba/all.aspx?lang=EN&amp;tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0" title="All Odds"><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div>
<div class="cdAllIn"><a href="/footba/all.aspx?lang=EN&amp;tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0" title="All Odds"><img src="/football/info/images/btn_odds.gif?CV=L302R1g" alt="All Odds" title="All Odds"></a></div>
""",'html.parser')

lines=soup.find_all('a')
for line in lines:
    print(line['href'])

结果:

/footba/all.aspx?lang=EN&tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0
/footba/all.aspx?lang=EN&tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0
/footba/all.aspx?lang=EN&tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0
/footba/all.aspx?lang=EN&tmatchid=6be0690b-93e3-4300-87e9-7d0aa5797ae0

预期结果:

6be0690b-93e3-4300-87e9-7d0aa5797ae0
6be0690b-93e3-4300-87e9-7d0aa5797ae0
6be0690b-93e3-4300-87e9-7d0aa5797ae0
6be0690b-93e3-4300-87e9-7d0aa5797ae0

2 个答案:

答案 0 :(得分:2)

由于只需要检索tmatchid值,因此请在网址中找到子字符串tmatchid =并从该索引中提取剩余的网址

lines=soup.find_all('a')
for line in lines:
    index=line['href'].find('tmatchid=')+9
    print(line['href'][index:])

输出

  

6be0690b-93e3-4300-87e9-7d0aa5797ae0
  6be0690b-93e3-4300-87e9-7d0aa5797ae0
  6be0690b-93e3-4300-87e9-7d0aa5797ae0
  6be0690b-93e3-4300-87e9-7d0aa5797ae0

答案 1 :(得分:2)

使用=分割字符串并获取最后一个索引。

for line in lines:
    print(line['href'].split('=')[-1])

希望这会有所帮助!干杯!