Python 从入门到爬虫极简教程
优采云 发布时间: 2020-08-15 10:59无联接: 请求之间不需要保持联接
媒介无关: MIME 类型确定数据内容
无状态: 用 cookie 或参数跟踪状态
请求头
通过观察 浏览器 -> 开发者工具 学习
重点把握
Cookie
Referer
User-Agent
Content-Type
请求方式GET
最常见, 一般通过 url 传递参数, 幂等性
POST
提交操作, 大量数据时, 上传文件时用
响应状态码
200:请求成功处理方法:获得响应的内容,进行处理
301:请求到的资源就会分配一个永久的URL,这样就可以在将来通过该URL来访问此资源 查看头里的 Location
302:请求到的资源在一个不同的URL处临时保存 查看头里的 Location
400:非法恳求
401:未授权
403:禁止
404:没有找到
500:服务器内部错误
502:错误网段 作为网段或则代理工作的服务器尝试执行恳求时,从上游服务器接收到无效的响应。
测试工具curl
结合浏览器的使用, -o 参数,
wget
断点续传之 -c 参数, 批量下载时的键值使用
chromium, telnet, netcatHTML 格式
学习工具
json
格式
工具
JavaScript & CSS
适当了解
python常用抓取工具/类库介绍urllib
import urllib2
response = urllib2.urlopen("http://www.baidu.com")
print response.read()
2to3 urllib.py
import urllib.request, urllib.error, urllib.parse
response = urllib.request.urlopen("http://example.com")
print(response.read())
练习指导:
Python3 启动, 退出 Ctrl+D2to3 --help 找出 -w 回写参数两种执行方法, 命令行, 交互式
参考:
Requests 库Scrapy
$ pip install Scrapy lxml
PySpider
非常便捷而且功能强悍的爬虫框架,支持多线程爬取、JS动态解析,提供了可操作界面、出错重试、定时爬取等等的功能,使用特别人性化。
官网
安装
$ pip install pyspider
使用
$ pyspider all
然后浏览器访问 :5000
Selenium & PhantomJS
$pip install selenium
用浏览器进行加载页面
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
驱动浏览器进行搜索
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
用 PhantomJS 保存页面为图片
PhantomJS 相当于无界面浏览器, 可执行脚本和 CSS 内存渲染
phantomjs helloworld.js
var page = require('webpage').create();
page.open('http://cuiqingcai.com', function (status) {
console.log("Status: " + status);
if (status === "success") {
page.render('example.png');
}
phantom.exit();
});
数据提取工具html, xml, xpath, selector, json正则表达式
掌握上去, 有一定难度, 多数编辑器支持, 使用场景广, 但不适宜结构化数据(xml, json, html)
Python Re模块提供
#返回pattern对象
re.compile(string[,flag])
#以下为匹配所用函数
re.match(pattern, string[, flags])
re.search(pattern, string[, flags])
re.split(pattern, string[, maxsplit])
re.findall(pattern, string[, flags])
re.finditer(pattern, string[, flags])
re.sub(pattern, repl, string[, count])
re.subn(pattern, repl, string[, count])
参见:
其于 Dom 模型的 jQuery selector
在 Selenium 中或浏览器中直接使用
基于查询语言的 XPath 标准
XPath语言是基于一个树状结构表示的XML 文档,提供的导航能力,通过多种属性选择节点的一个标准。
XPath 是提取 XML 的工具, 所以须要对 HTML正行校准
校正工具:
>>> from lxml import etree
>>> doc = ''
>>> tree = etree.HTML(doc)
>>> r = tree.xpath('/foo/bar')
>>> len(r)
1
>>> r[0].tag
'bar'
>>> r = tree.xpath('bar')
>>> r[0].tag
'bar'
最稳定的结果是使用 lxml.html 的 soupparser。你须要安装 python-lxml 和 python-beautifulsoup,然后你可以执行以下操作:
from lxml.html.soupparser import fromstring
tree = fromstring('here!')
matches = tree.xpath("./mal[@form=ed]")
XPath 文档
维基
W3C
入门教程
XPath 在线测试工具
特点: 可以直接加载 url
Johnny Dapp
Al Pacino
Robert De Niro
Kevin Spacey
Denzel Washington
Tata Consultancy Services
Wipro
Infosys
Microsoft
IBM
Apple
Oracle
示例:
1.选择文档节点
/
2.选择“root”元素
/root
3.选择所有'employee'元素,它们是'employees'元素的直接子元素。
/root/employees/employee
4.选择所有“公司”元素,无论它们在文档中的位置怎么。
//foo:company
5.选择“公司”元素的“id”属性,无论它们在文档中的位置怎么。
//foo:company/@id
6.选择第一个“employee”元素的文本值。
//employee[1]/text()
7.选择最后一个'employee'元素。
//employee[last()]
8.使用其位置选择第一个和第二个“employee”元素。
//employee[position()
9.选择具有“id”属性的所有“employee”元素。
//employee[@id]
10.选择'id'属性值为'3'的'employee'元素。
//employee[@id='3']
11.选择“id”属性值大于或等于“3”的所有“employee”节点。
//employee[@id
12.选择“companies”节点的所有子项。
/root/foo:companies/*
13.选择文档中的所有元素。
// *
14.选择所有“员工”元素和“公司”元素。
//employee|//foo:company
15.选择文档中第一个元素的名称。
name(//*[1])
16.选择第一个“employee”元素的“id”属性的数值。
number(//employee[1]/@id)
17.选择第一个“employee”元素的“id”属性的字符串表示方式值。
string(//employee[1]/@id)
18.选择第一个“employee”元素的文本值的厚度。
string-length(//employee[1]/text())
19.选择第一个“company”元素的本地名称,即没有命名空间。
string-length(//employee[1]/text())
20.选择“公司”元素的数目。
count(//foo:company)
21.选择'company'元素的'id'属性的总和。
sum(//foo:company/@id)
使用示例: 用xpath如何提取重复元素中的一个元素
<p class="title">序号
001
编号
999
列号
321
</p>
//p[text()="编号"]/following-sibling::p[1]
例如:Python+Selenium获取文本:
driver.driver.find_element_by_xpath(//p[text()="编号"]/following-sibling::p[1]).text
注: Selenium 支持 XPath 和类 jQuery Selector 等多种选择方法.
Firefox 和 XPath
2017之前的 firefox 版本 + Firebug
2017后 Firefox Developer Edition + Chropath addon
Chromium 和 XPath
在Chrome/ Firefox浏览器中打开网站
Chrome Extension XPath Helper (需要科学上网)
数据保存csv 及 excel 格式
注意顿号通配符, 可用现成库
MySQL 数据库
安装MySQL驱动
由于MySQL服务器以独立的进程运行,并通过网路对外服务,所以,需要支持Python的MySQL驱动来联接到MySQL服务器。MySQL官方提供了mysql-connector-python驱动,但是安装的时侯须要给pip命令加上参数--allow-external:
$ pip install mysql-connector-python --allow-external mysql-connector-python
如果里面的命令安装失败,可以试试另一个驱动:
$ pip install mysql-connector
我们演示怎么联接到MySQL服务器的test数据库:
# 导入MySQL驱动:
>>> import mysql.connector
# 注意把password设为你的root口令:
>>> conn = mysql.connector.connect(user='root', password='password', database='test')
>>> cursor = conn.cursor()
# 创建user表:
>>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
>>> cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
>>> cursor.rowcount
1
# 提交事务:
>>> conn.commit()
>>> cursor.close()
# 运行查询:
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user where id = %s', ('1',))
>>> values = cursor.fetchall()
>>> values
[('1', 'Michael')]
# 关闭Cursor和Connection:
>>> cursor.close()
True
>>> conn.close()
爬虫常见问题常见反爬技术User-Agent
新华网
Referer频度
用户点击才展示内容
博客
登录后可用内容
各种人机验证 Captcha封IP, 封ID编码问题 GB2312, GB18030, GKB, UTF-8, ISO8859-1
GB18030 > GBK > GB2312 但互相兼容
UTF-8与以上编码不兼容
用代理隐藏 ip
import requests
from lxml import etree
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
}
url = 'https://ip.cn/'
## 下面的网站是用来获取代理ip的API
ip_url = 'http://proxy.w2n1ck.com:9090/random'
ip = {'http' : 'http://'+requests.get(ip_url).text}
print(ip)
response = requests.get(url, headers=headers, proxies=ip, timeout=10).text
html = etree.HTML(response)
## 提取页面显示的ip
res = html.xpath('//*[@id="result"]/div/p[1]/code/text()')
print(res)
模拟登陆图形验证码处量百度OCR
Tesseract + openCVML-OCR
效果最好
人工OCR
手工录入
数据可视化matplotechartsTableau中级话题手机APP插口数据抓取
Python3.x+Fiddler抓取APP数据
思路是笔记本共享 wifi, 手机连这个 wifi, 电脑wifi 的 IP做为代理,手机上设置代理.
手机信任笔记本的代理证书.中间人攻击完成了.
截获到网路恳求再通过参数变换完成抓取
分布式爬虫
数据库或缓存为协调工具
中文动词
结巴动词
自然言语剖析
hanlp
tlp-cloud
人脸辨识
阿里的插口
图形辨识有问题到那里去问?
Coursera
思否
(c) 2018 Yujiaao