鱼C论坛

 找回密码
 立即注册
查看: 1775|回复: 3

爬取2019主要城市房价工资比为空列表

[复制链接]
发表于 2020-3-23 15:23:11 | 显示全部楼层
给你重写了一下
  1. import requests
  2. from bs4 import BeautifulSoup
  3. import re
  4. import openpyxl

  5. def open_url(url):
  6.     headers = {
  7.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'
  8.     }

  9.     res = requests.get(url, headers = headers)
  10.     res.encoding = 'utf-8'
  11.     return res


  12. def find_data(res):
  13.     data = []
  14.     soup = BeautifulSoup(res.text,'lxml')
  15.     content = soup.find('article',class_="article-content")
  16.     targets = content.find_all('p')[8:-13]
  17.     for i in range(len(targets)//5):
  18.         data.append([
  19.                 re.findall(r'\[(.+)\]',targets[i*5+1].text)[0],
  20.                 re.findall(r'\d.*',targets[i*5+2].text)[0],
  21.                 re.findall(r'\d.*',targets[i*5+3].text)[0],
  22.                 re.findall(r'\d.*',targets[i*5+4].text)[0]
  23.             ])
  24.     return data


  25. def to_excel(data):
  26.     wb = openpyxl.Workbook()
  27.     wb.guess_types = True
  28.     ws = wb.active
  29.     ws.append(['城市','平均房价','平均工资','房价工资比'])
  30.     for each in data:
  31.         ws.append(each)

  32.     wb.save("2019全国各大主要城市房价、工资排行榜.xlsx")


  33. def main():
  34.     url = 'http://www.szfce.com/gn/27107.html'
  35.     # url = 'https://news.house.qq.com/a/20170702/003985.htm'
  36.     res = open_url(url)
  37.     data = find_data(res)
  38.     to_excel(data)

  39. if __name__ == "__main__":
  40.     main()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-24 03:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表