學習 Python 的新手,但對 Google 表格非常熟悉——我本質上是在嘗試模仿“過濾器”功能,但在上面找不到任何東西。
我的腳本的目標是提取 NBA 球員的社交媒體標簽(來自 URL)。
我可以拉出所有鏈接,但想清理我的代碼,所以基本上有一個 if 陳述句說
如果我的結果包含 (https://www.facebook.com")、(https://www.twitter.com") 或 (https://www.instagram.com"),那將是唯一提取的資訊.
現在,它看起來更像這樣:
代碼結果
這不是世界末日,因為我可以粘貼到 Google 表格中并進行清理,但是學習這樣的東西真的很棒。
from bs4 import BeautifulSoup
import requests
def get_profile(url):
profiles = []
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
container = soup.find('div', attrs={'class', 'main-container'})
for profile in container.find_all('a'):
profiles.append(profile.get('href'))
for profile in profiles:
print(profile)
get_profile('https://basketball.realgm.com/player/Carmelo-Anthony/Summary/452')
get_profile('https://basketball.realgm.com/player/LeBron-James/Summary/250')
uj5u.com熱心網友回復:
您可以使用in關鍵字來搜索子字串。在您的情況下,您可以像這樣檢查每個組態檔:
if "https://www.facebook.com" in profile:
print(profile)
in如果找到子字串,則回傳 True。
uj5u.com熱心網友回復:
您可以搜索串列以檢查您正在檢查的特定 href 中是否存在任何專案,如下所示:
from bs4 import BeautifulSoup
import requests
def get_profile(url):
profiles = []
urls_to_keep = ['https://www.facebook.com', 'https://www.twitter.com', 'https://www.instagram.com']
req = requests.get(url)
soup = BeautifulSoup(req.text, 'html.parser')
container = soup.find('div', attrs={'class', 'main-container'})
for profile in container.find_all('a'):
href = profile.get('href')
if any(word in str(href) for word in urls_to_keep):
profiles.append(href)
for profile in profiles:
print(profile)
get_profile('https://basketball.realgm.com/player/Carmelo-Anthony/Summary/452')
get_profile('https://basketball.realgm.com/player/LeBron-James/Summary/250')
uj5u.com熱心網友回復:
您可以找到您需要的幾個值。any運算子用于此目的。
from bs4 import BeautifulSoup
import requests
def get_profile(url):
profiles = []
social_networks = ["https://www.facebook.com", "https://www.twitter.com", "https://www.instagram.com"]
req = requests.get(url)
for profile in BeautifulSoup(req.text, 'html.parser').find('div', attrs={'class', 'main-container'}).find_all('a'):
if profile.get('href') and any(link in profile.get('href') for link in social_networks):
profiles.append(profile.get('href'))
return profiles
print(get_profile('https://basketball.realgm.com/player/Carmelo-Anthony/Summary/452'))
print(get_profile('https://basketball.realgm.com/player/LeBron-James/Summary/250'))
輸出:
['https://www.facebook.com/CarmeloAnthony', 'https://www.instagram.com/carmeloanthony']
['https://www.facebook.com/LeBron', 'https://www.instagram.com/kingjames']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496221.html
上一篇:讓所有湯高于某個div
