我的代碼如下,提取所有元素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'])

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
您正在鏈接中搜索“about”,而“about”一詞似乎在鏈接['href']中找到。因此嘗試如下更新 if 條件。
print(link['href'] if 'about' in link['href'] else '')
添加回答
舉報
0/150
提交
取消