模板2之爬取城市房價

import requests
import bs4
import re
import openpyxl

def open_url(url):
	headers = {
		"user-agent": "F12可獲得"
		}
	res = requests.get(url,headers=headers)
	return res

def find_data(res):
	data = []
	soup = bs4.BeautifulSoup(res.text,"html.parser")
	content = soup.find(id="要尋找的內容")
	target = content.find_all("p",style="標籤";2em)
	target = iter(target)
	for each in target:
		if each.text.isnumeric():
			data.append([
				re.search(r'\[(.+)\]',next(target).text).group(1),
				re.search(r'\d.*',next(target).text).group(),
				re.search(r'\d.*',next(target).text).group(),
				re.search(r'\d.*',next(target).text).group()])
	return data

def to_excel(data):
	wb = openpyxl.workbook() # 創建一個工作簿,可包含很多sheet工作表。
	wb.guess_types = True
	ws = wb.active # 創建一個工作表
	ws.append(['城市','平均房價','平均工資','房價工資比']) # 標籤,寫入第一行
	for each in data:
		ws.append(each)
	ws.save("1.xlsx")

def main():
	url = "網址"
	res = open_url(url)
	data = find_data(res)
	to_excel(data)

main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章