Fork me on GitHub

Python_Spider_requests

requests

image

爬取网页的通用代码框架

1
2
3
4
5
6
7
8
def getHTMLText(url):
try:
r=requests.get(url,timeout30)
r.raise_for_status #如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding # 将编码格式转换为响应内容的编码格式
return r.text
ecxept:
return #产生异常
1
2
3
4
5
6
7
8
9
10
11
import requests
from requests.exceptions import RequestException
def page_state(rep):
url = " "
try:
rep = requests.get(url)
if rep.status_code == 200: # 如果状态码正常,则返回url的内容
return rep.text
return None
except:
return None

解释

requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多
requests.get()用于请求目标网站,类型是一个HTTPresponse类型

基本操作

1
2
3
4
5
6
7
8
9
import requests

response = requests.get('http://www.baidu.com')
print(response.status_code) # 打印状态码
print(response.url) # 打印请求url
print(response.headers) # 打印头信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印网页源码
print(response.content) #以字节流形式打印

GET请求相关内容

传入参数
  • 第一种直接将参数放在url内

    1
    2
    3
    4
    import requests
    #url/get?参数&参数
    response = requests.get(http://httpbin.org/get?name=gemey&age=22)
    print(response.text)
  • 第二种先将参数填写在dict中,发起请求时params参数指定为dict

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import requests

    data = {
    'name': 'Jedieal',
    'age': 18
    }

    response = requests.get('http://httpbin.org/get', params=data)
    print(response.text)

案例 百度搜索

1
2
3
import requests
kv = {'wd':'python'}
r = requests.get("http://www.baidu.com/s",params=kv)


请求添加头信息
1
2
3
4
5
6
import requests
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \
'(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \
'(KHTML, like Gecko) Version/5.1 Safari/534.50'
response = requests.get('http://www.baidu.com',headers=headers)

#####访问响应头字段

1
2
3
4
5
6
7
r.headers['Content-Type]

'application/json'

r.headers.get('content-type')

'application/json'


使用代理

同添加headers方法,代理参数也要是一个dict
: 这里使用requests库爬取了IP代理网站的IP与端口和类型
因为是免费的,使用的代理地址很快就失效了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import requests
import re

def get_html(url):
proxy = {
'http': '120.25.253.234:812',
'https': '163.125.222.244:8123'
}
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
req = requests.get(url, headers=heads,proxies=proxy)
html = req.text
return html

#利用正则匹配IP
def get_ipport(html):
regex = r'<td data-title="IP">(.+)</td>'
iplist = re.findall(regex, html)
regex2 = '<td data-title="PORT">(.+)</td>'
portlist = re.findall(regex2, html)
regex3 = r'<td data-title="类型">(.+)</td>'
typelist = re.findall(regex3, html)
sumray = []
for i in iplist:
for p in portlist:
for t in typelist:
pass
pass
a = t+','+i + ':' + p
sumray.append(a)
print('高匿代理')
print(sumray)


if __name__ == '__main__':
url = 'http://www.kuaidaili.com/free/'
get_ipport(get_html(url))


获取cookie
1
2
3
4
5
6
7
8
import requests

response = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
#字典形式,利用items()遍历
for k,v in response.cookies.items():
print(k+':'+v)


解析json
1
2
3
4
5
6
7
import requests

response = requests.get('http://httpbin.org/get')
print(response.text)
#response.json()方法同json.loads(response.text)
print(response.json())
print(type(response.json()))


保存一个二进制文件

二进制内容为response.content

1
2
3
4
5
6
import requests

response = requests.get('http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg')
b = response.content
with open('F://fengjing.jpg','wb') as f:
f.write(b)


超时异常捕获
1
2
3
4
5
6
7
8
import requests
from requests.exceptions import ReadTimeout

try:
res = requests.get('http://httpbin.org', timeout=0.1)
print(res.status_code)
except ReadTimeout:
print('timeout')


异常处理

使用try…except来捕获异常

Exceptions:

1
2
3
4
5
6
7
8
9
10
11
12
import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException

try:
response = requests.get('http://www.baidu.com',timeout=0.5)
print(response.status_code)
except ReadTimeout:
print('timeout')
except HTTPError:
print('httperror')
except RequestException:
print('reqerror')


POST 请求

通常,你想要发送一些编码为表单形式的数据——非常像一个 HTML 表单。要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典在发出请求时会自动编码为表单形式:

1
2
3
4
payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

1
2
3
4
5
6
7
8
9
payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
>>>"form": {
"key1": [
"value1",
"value2"
]
}

很多时候你想要发送的数据并非编码为表单形式的。如果你传递一个 string 而不是一个dict,那么数据会被直接发布出去。
可以使用 json 参数直接传递,然后它就会被自动编码。这是 2.4.2 版的新加功能:

1
2
3
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)

喜欢的可以对我打赏了哟~