爬虫入门

目录

  1. Requests 自动爬取HTML页面;自动网络请求提交
  2. robots.txt 网络爬虫排除标准
  3. Beautiful Soup 解析HTML页面;信息标记与提取方法

Requests 库入门

安装requests库:pip install requests

测试requests库:

>>> import requests
>>> r = requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> r.encoding = 'utf-8'
>>> r.text
'!<DOCTYPE html> ......'

Response对象的属性

属性 说明
r.status_code HTTP状态码
r.text HTTP响应内容的字符串形式
r.encoding header中的响应编码方式
r.apparent_encoding 备选编码方式
r.content HTTP内容的二进制形式

网络爬虫的尺寸

规模
小规模,速度不敏感 Requests库
中规模,速度敏感 Scrapy库
全网数据 定制开发

Robots协议

Robots Exclusion Standard 网络爬虫排除标准

如:京东Robots协议 https://www.jd.com/robots.txt

User-agent: * 
Disallow: /?* 
Disallow: /pop/*.html 
Disallow: /pinpai/*.html?* 
User-agent: EtaoSpider 
Disallow: / 
User-agent: HuihuiSpider 
Disallow: / 
User-agent: GwdangSpider 
Disallow: / 
User-agent: WochachaSpider 
Disallow: /

修改请求头

import requests
url = "https://www.amazon.cn/gp/product/xxx"
try:
    kv = {'user-agent': 'Mozilla/5.0'}
    r = requests.get(url, headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    // 打印1000-2000行的内容
    print(r.text[1000:2000])
    // 打印响应的长度
    print(len(r.text))
except:
    print("爬取失败")

图片爬取全代码

import requests
import os
url = "http://image.xxx.com/sss.jpg"
root = "D://pics//"
path = root + url.split('/')[-1]
try:
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r = requests.get(url)
        with open(path, 'wb') as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件已存在")
except:
    print("爬取失败")
文章作者: koral
文章链接: http://luokaiii.github.io/2020/10/22/爬虫/入门/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自