亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何提取包含匹配字符串的字符串

如何提取包含匹配字符串的字符串

慕姐4208626 2024-01-15 21:38:52
我的代碼如下,提取所有元素for link in soup.find_all('a', href=True):    print(link['href'])輸出https://www.example.com/author/1/https://www.example.com/about/2/https://www.example.com/author/3/(link['href']) 的類型<cls str><cls str><cls str>我需要提取包含“about”的網址我嘗試用print(link['href'] if 'about' in link)哪個拋出錯誤我的預期結果https://www.example.com/about/2/
查看完整描述

2 回答

?
慕村9548890

TA貢獻1884條經驗 獲得超4個贊

條件表達式需要一個else子句來指定當條件為 false 時表達式應返回的內容。


但在這種情況下您不想打印任何內容。因此,請if在print()調用周圍使用聲明。


for link in soup.find_all('a', href=True):

    if 'about' in link['href']:

        print(link['href'])

您也可以在通話中進行匹配soup.find_all()。


for link in soup.find_all('a', href=re.compile(r'about')):

    print(link['href'])


查看完整回答
反對 回復 2024-01-15
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

您正在鏈接中搜索“about”,而“about”一詞似乎在鏈接['href']中找到。因此嘗試如下更新 if 條件。

print(link['href'] if 'about' in link['href'] else '')


查看完整回答
反對 回復 2024-01-15
  • 2 回答
  • 0 關注
  • 175 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號