Python笔记本

爬虫基本原理

爬虫是请求网站提取数据的自动化程序


爬虫的基本流程

  1. 发起请求:通过http库想目标站点发送请求
  2. 如果服务器响应,会得到一个response
  3. 解析内容
  4. 保存数据,保存成文本或者至数据库
#!/usr/bin/env python
# encoding: utf-8

import requests
response = requests.get('http://www.baidu.com')
print response.headers
print response.status_code
print response.text


能抓取怎么样的数据

  1. 抓取网页文本
  2. 抓取图片
  3. 视频
  4. 其他
#!/usr/bin/env python
# encoding: utf-8

import requests
response = requests.get('https://ss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin_zoom/178.jpg?2')
with open('e:/aaa.jpg', 'wb') as f:
    f.write(response.content)
    f.close()


有哪些解析方式

  1. 直接处理(网页构造简单、返回的内容简单)
  2. Json解析(返回Json的字符串)
  3. 正则表达式
  4. BeatifulSoup
  5. PyQuery
  6. Xpath


怎么解决javascript渲染的问题,获取的网页和浏览器打开的网页内容不一致,如下

#!/usr/bin/env python
# encoding: utf-8

import requests
response = requests.get('https://m.weibo.cn/')
print response.headers
print response.status_code
print response.text

  1. 分析Ajax请求
  2. selenium/WebDriver
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://m.weibo.cn/')
#driver.get('https://www.zhihu.com/')
print driver.page_source

    3. Splash

    4. PyV8、Ghost.py


怎么样来保存数据

  1. 纯文本
  2. 关系型数据库
  3. 非关系型数据库
  4. 二进制文件

猜你喜欢

转载自blog.csdn.net/l4642247/article/details/81015234