使用requests_html抓取数据

2020-09-17 10:31:32 浏览数 (1)

代码语言:javascript复制
from requests_html import HTMLSession
import json

class YejiCollege:
    def __init__(self, url):
        self.url = url
        self.headers = {"User-Agent": ("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36")}

    def get_response(self):
        session = HTMLSession()
        return session.get(self.url, headers=self.headers)

    def filter_info(self):
        html_data = self.get_response()
        # 从第三个P标签开始,获取虚假大学数据
        return html_data.html.find('div#data249708 p')[2:]

    @staticmethod
    def get_json(data):
        info = {}
        city = None
        for line in data:
            # 每个城市会显示为 <p><strong>北京:151所</strong></p>
            if 'strong' in line.html:
                # 拆分城市与虚假大学数量
                city, total_college = line.text.split(':')
                # 构造字典
                info[city] = dict(total=total_college, data=[])
                continue
            info[city]['data'].append(line.text)
        with open('colleges.json', 'w ', encoding='utf-8') as f:
            # ensure_ascii默认为True,json.dump后会被转码...
            f.write(json.dumps(info, ensure_ascii=False))

def run():
    url = 'http://www.gaosan.com/gaokao/249708.html'
    main = YejiCollege(url)
    data = main.filter_info()
    main.get_json(data)

if __name__ == '__main__':
    run()

结果:

代码语言:javascript复制
  ... ... ,
  "陕西": {
    "total": "16所",
    "data": [
      "西安电子信息学院",
      "西安理工学院",
      "西安工商学院",
      "西安科技师范大学",
      "西安信息技术学院",
      "西安工商管理学院",
      "西安工业科技技术学院",
      "西安工业科技学院",
      "陕西国防工业技术学院",
      "陕西瀚林医科学院",
      "西安工业工程学院",
      "陕西工贸职业学院",
      "西安科技职业学院",
      "西安经济技术学院",
      "西安机电工程学院",
      "陕西科技管理学院"
    ]
  },
  "福建": {
    "total": "5所",
    "data": [
      "厦门师范学院",
      "福建海峡经贸技术学院",
      "福建经济贸易大学",
      "福建科技学院",
      "福建省轻工业学院"
    ]
  },
  ... ...

文章参考于微信公众号【清风Python】

0 人点赞