1 回答

TA貢獻1804條經驗 獲得超7個贊
為抓取添加一個配置,其中每個配置都是這樣的:
prices = {
"LIVEAUOZ": {
"url": "https://www.gold.co.uk/",
"trader": "Gold.co.uk",
"metal": "Gold",
"type": "LiveAUOz",
"price": {
"selector": '#id > div > table > tr',
"parser": lambda x: float(re.sub(r"[^0-9\.]", "", x))
}
}
}
使用 price 的選擇器部分獲取 HTML 的相關部分,然后使用解析器函數對其進行解析。
例如
for key, config in prices.items():
response = requests.get(config['url'])
soup = BeautifulSoup(response.text, 'html.parser')
price_element = soup.find(config['price']['selector'])
if price_element:
AG_GRAM_SPOT = price_element.get_text()
# convert to float
AG_GRAM_SPOT = config['price']['parser'](AG_GRAM_SPOT)
# etc
您可以根據需要修改配置對象,但對于大多數站點來說它可能非常相似。例如,文本解析很可能總是相同的,所以不用 lambda 函數,而是用 def 創建一個函數。
def textParser(text):
return float(re.sub(r"[^0-9\.]", "", text))
然后在配置中添加對 textParser 的引用。
prices = {
"LIVEAUOZ": {
"url": "https://www.gold.co.uk/",
"trader": "Gold.co.uk",
"metal": "Gold",
"type": "LiveAUOz",
"price": {
"selector": '#id > div > table > tr',
"parser": textParser
}
}
}
這些步驟將允許您編寫通用代碼,保存所有那些嘗試異常。
添加回答
舉報