爬虫:可以把互联网看做是一张大网,爬虫就好像是这张网里的蜘蛛,如果想得到这张网里的资源,就可以将其抓取下来。
简单来说就是请求网站并提取数据的自动化程序。
爬虫的基本流程:
Request和Response过程:
(1)浏览器就发送消息给该网址所在的服务器,这个过程就叫做HTTP Request
(2)服务器收到浏览器发送的消息后,能够根据浏览器发送消息的内容,做相应的处理,然后把消息回传给浏览器,这个过程就叫做HTTP Response
(3)浏览器收到服务器的Response信息后,会对信息进行处理并展示。
Request请求:
Response响应:
简单实例:
import requests response= requests.get(‘http://www.baidu.com‘) print(response.text) # 得到响应体 print(response.headers) # 得到相应头 print(response.status_code) # 状态码
能抓什么样的数据?
数据处理:
怎么保存数据
小例子:
爬取https://www.autohome.com.cn/news/页面上的a标签的href和图片,并将图片保存于本地
import requests
from bs4 import BeautifulSoup
response = requests.get(
url=‘https://www.autohome.com.cn/news/‘
)
response.encoding = response.apparent_encoding # 解决乱码
soup = BeautifulSoup(response.text,features=‘html.parser‘)
target = soup.find(id=‘auto-channel-lazyload-article‘)
li_list = target.find_all(‘li‘)
for i in li_list: # 每一个i就是一个soup对象,就可以使用find继续找
a = i.find(‘a‘) # 如果找不到a,调用a.attrs就会报错,所有需要判断
if a:
a_href = a.attrs.get(‘href‘)
a_href = ‘http:‘ + a_href
print(a_href)
txt = a.find(‘h3‘).text
print(txt)
img = a.find(‘img‘).attrs.get(‘src‘)
img = ‘http:‘ + img
print(img)
img_response = requests.get(url=img)
import uuid
filename = str(uuid.uuid4())+ ‘.jpg‘
with open(filename,‘wb‘) as f:
f.write(img_response.content)
简单总结:
‘‘‘ response = request.get(‘url‘) response.text resopnse.content response.encoding response.encoding = response.apparent_encoding response.status_code ‘‘‘ ‘‘‘ soup = BeautifulSoup(response.text,features=‘html.parser‘) v1 = soup.find(‘div‘) # 找到第一个符合条件的 soup.find(id=‘i1‘) soup.find(‘div‘,id=‘i1‘) v2 = soup.find_all(‘div‘) obj = v1 obj = v2[0] # 从列表中按索引取到每一个对象 obj.text obj.attrs # 属性 ‘‘‘
1、调用的方法关系
‘‘‘‘
requests.get()
requests.post()
requests.put()
requests.delete()
...
上面这些方法本质上都是调用的是requests.request()方法,例如:
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault(‘allow_redirects‘, True)
return request(‘get‘, url, params=params, **kwargs)
‘‘‘
2、常用参数:
‘‘‘
requests.request()
- method:提交方式
- url: 提交地址
- params:在URL上传递的参数,GET,例如
requests.request(
method=‘GET‘,
url=‘http://www.baidu.com‘,
params={‘username‘:‘user‘,‘password‘:‘pwd‘}
)
# http://www.baidu.com?username=user&password=pwd
- data:在请求体里传递的数据
requests.request(
method=‘POST‘,
url=‘http://www.baidu.com‘,
data={‘username‘:‘user‘,‘password‘:‘pwd‘}
)
- json:在请求体里传递的数据
requests.request(
method=‘POST‘,
url=‘http://www.baidu.com‘,
json={‘username‘:‘user‘,‘password‘:‘pwd‘}
)
# json="{‘username‘:‘user‘,‘password‘:‘pwd‘}" 整体发送
- headers:请求头
requests.request(
method=‘POST‘,
url=‘http://www.baidu.com‘,
json={‘username‘:‘user‘,‘password‘:‘pwd‘},
headers={
‘referer‘:‘https://dig.chouti.com/‘,
‘user-agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36‘
}
)
- cookies: cookies,一般放在headers发过去。
‘‘‘
原文:https://www.cnblogs.com/crazyforever/p/9074652.html