【博学谷学习记录】超强总结,用心分享 | 文字爬虫

【博学谷IT技术支持】
目的: 抓取网站文字

一、使用到的python库

requests库

// 安装

pip install requests

// 导入
import requests

// header
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)


// get使用
r = requests.get('https://api.github.com/events')

// get请求传递参数
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://httpbin.org/get', params=payload)


// post使用
r = requests.post('url', data = {'key': 'value'})

// json响应内容
r.json()

// 保存文件

with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)

BeautifulSoup

BeautifulSoup是一个可以从HTML或XML文件中提取数据的python库。

// 安装
pip install beautifulsoup4

// 使用

from bs4 import BeautifulSoup
soup = BeautifulSoup(open("index.html"))

二、实际操作

首先知道要操作的网站,如:http://demo.mxyhn.xyz:8020/cssthemes6/oyqj-0924-18/index.html

  • 首先我们要获取网页
import requests

def down_html():
  # 下载页面
 
  url = 'http://demo.mxyhn.xyz:8020/cssthemes6/oyqj-0924-18/index.html'
  r = requests.get(url)
  html = r.text
  return html
html = down_html()

以上代码我们就获取到了当前页面

  • 解析页面

解析页面的时候,要有目标,比如说解析导航页的文字

先解析页面

image.png

看到dom结构,知道了导航是在nav的一个节点里,这个节点会有多个li子节点,li子节点里还有a标签,a标签里有要拿的文字。

那么获取这个数据就要一层一层的往下循环

from bs4 import BeautifulSoup

def parse_html_title(html):
  # 解析HTML
  soup = BeautifulSoup(html)
  body = soup.find('body')

  header_node = body.find('nav', class_='navbar')
  nav_nodes = header_node.find('ul', class_='navbar-nav').find_all('li')
  navs = [nav_node.get_text() for nav_node in nav_nodes]

  return {'navList': navs}

datas = parse_html_title(html)

拿到数据后,要将数据保存起来

  • 保存数据
with open('site.json', 'wb') as fout:
  fout.write(json.dumps(datas, ensure_ascii=False).encode('utf-8')+b'\n')
  • json.dumps: 将 Python 对象编码成 JSON 字符串

  • json.loads: 将已编码的 JSON 字符串解码为 Python 对象

  • 执行文件

python site.py

执行后得到json文件

image.png

posted @ 2023-01-21 21:26  牛牛牛牛牛牛牛牛  阅读(10)  评论(0编辑  收藏  举报