我想在以“https://freecash.com/auth/”開頭的 JSON(請求回應)中找到一個 URL。我希望它只列印那個而不是其他的東西,我該怎么做?
請求的代碼:
z = requests.get(f"https://www.1secmail.com/api/v1/?action=readMessage&login={user}&domain={dom}&id={z[c]['id']}").json()
這是我試圖找到那個確切的東西的地方:
{z['body']
它既不是開始也不是結束。我將如何搜索它?我也需要它只列印 URL,而不是回應的其余部分。
uj5u.com熱心網友回復:
您可以將 re 模塊 wichis 用于正則運算式
重新進口
#檢查字串是否以“http://url1267”開頭并以“string_end”結尾:
json_response = "西班牙的雨" x = re.search("^http://url1267.*'string_end'$", json_response)
完全根據您的情況更改 string_end
uj5u.com熱心網友回復:
撰寫一個輔助函式,該函式將展平并遍歷 JSON 物件中的值:
def get_values_from_json(obj):
if type(obj) is dict:
for item in obj.values():
yield from get_values_from_json(item)
elif type(obj) is list:
for item in obj:
yield from get_values_from_json(item)
else:
yield obj
然后遍歷這些,尋找所需的模式:
for item in get_values_from_json(z["body"]):
if item.startswith("http://url1267"): # or use regex if this is more complicated
print(item)
編輯
從對另一個答案的評論中,很明顯您實際上是在搜索恰好是 JSON 請求一部分的 html 頁面。freecash.com您可以使用在引號 ("或')內查找的正則運算式進行搜索。
import re
for i, item in enumerate(re.findall(r'["\']([^"\']*?freecash\.com[^"\']*?)["\']', z["body"])):
print(i, item)
另一種可能更清潔的解決方案是使用 BeautifulSoup,它將正確決議 html 內容并在適當的背景關系中查找鏈接:
from bs4 import BeautifulSoup
soup = BeautifulSoup(z["body"], features="lxml")
for tag in soup.find_all("a"):
link = tag.get("href")
if "freecash.com" in link:
print(link)
uj5u.com熱心網友回復:
閱讀您的 JSON 檔案,然后讀取類似的內容:
z = requests.get(f"https://www.1secmail.com/api/v1/?action=readMessage&login={user}&domain={dom}&id={z[c]['id']}").json()
for line in z:
line = line.rstrip()
if line.startswith('http://url1267'):
print(line)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504575.html
上一篇:OSError:[Errno22]帶有\r的無效引數
下一篇:幾乎是ISO8601格式
