嘗試從 HTML 檔案中抓取資料,其中包含一個 react props DIV,如下所示:
<html>
<div data-react-class="UserDetails"
data-react-props="{
"targetUser
":{
"targetUserLogin":"user",
"targetUserDuration":"11 months, 27 days","""
}
}
我要找的是日期!比如 11 個月 27 天,所以我可以把它們加起來得到確切的“天數”
我不知道如何準確地獲取這些資料,因為不同的人可能正好是 2 年,而且文本中不會出現任何日子。我需要年和日,所以我可以計算。所以我寫了這個來找到我需要的代碼部分,但我不知道如何處理其余部分..
with open("data.html", 'r') as fpIn:
for line in fpIn:
line = line.rstrip() # Strip trailing spaces and newline
if "targetUserDuration" in line:
print("Found")
uj5u.com熱心網友回復:
使用正則運算式找到它。
import re
html = '..."targetUserDuration":"11 months, 27 days","""...'
years_re = re.compile(r'UserDuration".*?([1-9] ) year.*?"""')
months_re = re.compile(r'UserDuration".*?([1-9]|1[0-2]) month.*?"""')
days_re = re.compile(r'UserDuration".*?([1-9]|2[0-9]|3[0-1]) day.*?"""')
year_found = years_re.search(html)
months_found = months_re.search(html)
days_found = days_re.search(html)
years, months, days = 0, 0, 0
if year_found:
years = int(year_found.group(1))
if months_found:
months = int(months_found.group(1))
if days_found:
days = int(days_found.group(1))
print('years: ', years)
print('months: ', months)
print('days: ', days)
結果:
years: 0
months: 11
days: 27
uj5u.com熱心網友回復:
我可能會先看“BeautifulSoup”。我認為它會自動轉義。我知道要加載更多的庫,但我會使用它html.unescape(),json.loads()因為這似乎很自然地適合提供資料的方式,而不是嘗試自己決議它。手動決議在這里似乎不必要地脆弱。
from html import unescape
from json import loads
text = """
{
"targetUser":{
"targetUserLogin":"user",
"targetUserDuration":"11 months, 27 days"
}
}
"""
print(loads(unescape(text))["targetUser"]["targetUserDuration"])
給你:
11 months, 27 days
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427427.html
標籤:Python python-3.x
下一篇:通過存盤在物件中的名稱執行函式
