Python 爬虫之 Requests

Requests 是小型静态网页爬取项目的首选,易用且够用。

工作流程一般为,使用Requests获取内容(比urlliburllib2方便),用lxml分析(比BeautifulSoup快10倍)。

Requests使用

Requests中文文档

import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
r = requests.post("http://httpbin.org/post", data=payload)

会话对象requests.Session()让你能够请求保持某些参数,它也会在同一个会话实例发出的所有请求之间保持cookies。

s = requests.Session()
s.headers.update({'User-agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'})
r = s.get("http://httpbin.org/cookies")

r.headers['content-type']可以判断打开的文件类型。如对PDF'application/pdf;charset=UTF-8',对png图片有'image/png'网页可以看到常见文件类型的content-type

代理

import requests
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",    }
requests.get("http://example.org",     proxies=proxies)

如果要socks代理

import requesocks as requests
session = requests.session()
session.proxies = {
    'http': 'socks5://127.0.0.1:8087', 
    'https': 'socks5://127.0.0.1:8087'}
session.get('http://example.org')

url

url编码

urllib.quoteurllib.unquote可以转换链接中的特殊字符。也可以使用requests.utils.quote

关于url编码的介绍可见这里

相对路径

import urlparse
urlparse.urljoin(r.url, url)

url解析

u = urlparse.urlsplit(url)
#scheme, hostname, port, path, query, fragment

压缩?

在HTTP请求里面加上Accept-Encoding头部,将其设为gzip即可,表示可以接受gzip压缩的数据,绝大多数网站都支持gzip压缩,可以节省70 ~ 80%的流量

lxml使用

lxml主要使用etree类。

from lxml import etree
p = etree.HTML(r.content)

#找所有层级的标签p
p.xpath(u"//p")

#找拥有指定class属性的标签p
p.xpath(u"/html/body/p[@class='xw']")

#找文本为指定内容的标签div
p.xpath("div[.='hello']")
p.xpath("div[text()='hello']")

#body下第1个div
p.xpath('body/div[1]')

#所有文本中含有jpg的链接
p.xpath('//a[contains(text(),"jpg")]')
#还可以是starts-with、ends-with

#xpath中出现中文时,可以这样解决
p.xpath("//span[contains(., '%s')]" %u'下一页')

#注意p.text和p.tail可能并不完全,最好使用如下方式
#访问本节点所有文本信息
p.xpath('text()')
#包括子结点的文本信息
p.xpath('.//text()')

//a[@href='help.php'][name(..)='div'][../@class='header']/@target

此例将会选择符合条件的元素a的target属性。 要求元素a:

  • 具有属性href且值为help.php;

  • 并且元素a具有父元素div;

  • 并且父元素(div)其自身具备class属性,值为header。

其他xpath可用函数见此

模块lxml.html.clean 提供 一个Cleaner 类来清理 HTML 页,它支持删除嵌入或脚本内容、 特殊标记、 CSS 样式注释或者更多。

测试

httpbin.org是一个专门用于测试网络软件的网站。

标签: python, 爬虫

赞 (6)

添加新评论