requests与BeautifulSoup
requests模块:
1、安装:pip install requests
2、使用request发送get请求:
import requests
paras = {
'k1':'c1',
'k2':'c2'
}
ret = requests.get('https://www.cnblogs.com/qiangayz/p/9563377.html')
print(ret.url)
ret = requests.get('https://www.cnblogs.com/qiangayz/p/9563377.html', params=paras)
print(ret.url)
3、使用request发送post请求:
import requests
import json
paras = {
'k1':'v1',
'k2':'v2',
}
requests.post('https://www.cnblogs.com/qiangayz/p/9563377.html')
headers_data = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
requests.post('https://www.cnblogs.com/qiangayz/p/9563377.html',
headers=headers_data,
data=json.dumps(paras),
)
4、requests初始化其他可选参数:
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
: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 data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
"""
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
参数说明:
-- method:请求方式:post、get等
-- url :请求的网址url
-- params:在url上传递的参数
例:
paras = {
'k1':'c1',
'k2':'c2'
}
requests.get('https://www.cnblogs.com/qiangayz/p/9563377.html', params=paras)
实际url是:
https://www.cnblogs.com/qiangayz/p/9563377.html?k1=c1&k2=c2
-- data:在请求体里面传递的数据,请求头为:
headers={'Content-Type': 'application/x-www-form-urlencoded'}
-- json:也是在请求题里面传递数据,与data不同的是请求头不一样,且json数据可以嵌套字典
请求头为:
headers={'Content-Type': 'application/x-www-form-urlencoded'}
-- headers:请求头
-- cookies:网站cookies
-- files:上传文件:
requests.post(
url='127.0.0.1',
files={
'f1': open('xxx.txt', 'rb'), #文件名使用默认的
'f2':('XXX.txt', open('xxx.txt', 'rb')) #使用定制的文件名
}
)
-- auth:简易认证,将与户名和密码加密之后放到请求头里面发送过去
-- timeout :超时
-- allow_redirects:是否允许重定向
-- proxies:使用代理
-- stream:使用流
-- verify :证书,http与https的区别,https可以使用证书来加密消息,该值可以是False或者True,False代表不接受证书,忽略证书
-- cert:证书文件
5、requests.session的使用:
保存客户端历史访问信息
import requests
session = requests.Session()
#首先登陆页面获取cookies
l1 = session.get(url='xxxxx')
#用户登录,携带上一次的cookies
l2 = session.post(
url='xxx',
data='',
)
BeautifulSoup模块:
1、安装:
pip install beautifulsoup4
2、基本使用
from bs4 import BeautifulSoup
import htmldoc
html_doc = htmldoc.html_doc
soup = BeautifulSoup(html_doc,features='html.parser')
#找到一个a标签
tag1 = soup.find(name='a')
print(tag1.name,tag1.attrs)
#找到所有a标签
tag2 = soup.find_all(name='a')
print(tag2)
#找到id为inputuser的标签
tag3 = soup.select('#inputuser')[0]
print(tag3.name,tag3.attrs)
3、标签的方法:
1、tag1.name获取标签名称
tag1.name='span' 给标签赋值
2、tag1.attrs获取标签的属性值,字典类型
tag1.attrs=dict1设置值
tag1.attrs['id'] = 'a123'设置值
del tag1.attrs['id'] 删除属性
3、tags.children找子标签
from bs4 import BeautifulSoup
import htmldoc
from bs4.element import Tag
html_doc = htmldoc.html_doc
soup = BeautifulSoup(html_doc,features='html.parser')
tags = soup.find(name='body').children
tags_list = []
for item in tags:
if type(item) == Tag:
tags_list.append(item)
4、tag.descendants
tags = soup.find(name='body').descendants #找子子孙孙,第一个递归完才开始找第二个 print(len(list(tags)))
5、tag. clear,将标签的所有子标签清空(保留标签名)
6、tag.decompose,递归的删除所有的标签,(不保留当前标签名)
7、tag.extract,递归的删除所有的标签,并返回删除的标签,类似于列表的pop方法
8、tag.decode,转换为字符串(含当前标签);tag.decode_contents(不含当前标签)
9、tag.encode,转换为字节(含当前标签);tag.encode_contents(不含当前标签)
10. find,获取匹配的第一个标签
|
1
2
3
4
5
|
# tag = soup.find('a')# print(tag)# tag = soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')# tag = soup.find(name='a', class_='sister', recursive=True, text='Lacie')# print(tag) |
11. find_all,获取匹配的所有标签
|
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# tags = soup.find_all('a')# print(tags)# tags = soup.find_all('a',limit=1)# print(tags)# tags = soup.find_all(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')# # tags = soup.find(name='a', class_='sister', recursive=True, text='Lacie')# print(tags)# ####### 列表 ######## v = soup.find_all(name=['a','div'])# print(v)# v = soup.find_all(class_=['sister0', 'sister'])# print(v)# v = soup.find_all(text=['Tillie'])# print(v, type(v[0]))# v = soup.find_all(id=['link1','link2'])# print(v)# v = soup.find_all(href=['link1','link2'])# print(v)# ####### 正则 #######import re# rep = re.compile('p')# rep = re.compile('^p')# v = soup.find_all(name=rep)# print(v)# rep = re.compile('sister.*')# v = soup.find_all(class_=rep)# print(v)# rep = re.compile('http://www.oldboy.com/static/.*')# v = soup.find_all(href=rep)# print(v)# ####### 方法筛选 ######## def func(tag):# return tag.has_attr('class') and tag.has_attr('id')# v = soup.find_all(name=func)# print(v)# ## get,获取标签属性# tag = soup.find('a')# v = tag.get('id')# print(v) |
12. has_attr,检查标签是否具有该属性
|
1
2
3
|
# tag = soup.find('a')# v = tag.has_attr('id')# print(v) |
13. get_text,获取标签内部文本内容
|
1
2
3
|
# tag = soup.find('a')# v = tag.get_text()# print(v) |
14. index,检查标签在某标签中的索引位置
|
1
2
3
4
5
6
7
|
# tag = soup.find('body')# v = tag.index(tag.find('div'))# print(v)# tag = soup.find('body')# for i,v in enumerate(tag):# print(i,v) |
15. is_empty_element,是否是空标签(是否可以是空)或者自闭合标签,
判断是否是如下标签:'br' , 'hr', 'input', 'img', 'meta','spacer', 'link', 'frame', 'base'
|
1
2
3
|
# tag = soup.find('br')# v = tag.is_empty_element# print(v) |
16. 当前的关联标签
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
# soup.next# soup.next_element# soup.next_elements# soup.next_sibling# soup.next_siblings## tag.previous# tag.previous_element# tag.previous_elements# tag.previous_sibling# tag.previous_siblings## tag.parent# tag.parents |
17. 查找某标签的关联标签
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# tag.find_next(...)# tag.find_all_next(...)# tag.find_next_sibling(...)# tag.find_next_siblings(...)# tag.find_previous(...)# tag.find_all_previous(...)# tag.find_previous_sibling(...)# tag.find_previous_siblings(...)# tag.find_parent(...)# tag.find_parents(...)# 参数同find_all |
18. select,select_one, CSS选择器
|
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
soup.select("title")soup.select("p nth-of-type(3)")soup.select("body a")soup.select("html head title")tag = soup.select("span,a")soup.select("head > title")soup.select("p > a")soup.select("p > a:nth-of-type(2)")soup.select("p > #link1")soup.select("body > a")soup.select("#link1 ~ .sister")soup.select("#link1 + .sister")soup.select(".sister")soup.select("[class~=sister]")soup.select("#link1")soup.select("a#link2")soup.select('a[href]')soup.select('a[href="http://example.com/elsie"]')soup.select('a[href^="http://example.com/"]')soup.select('a[href$="tillie"]')soup.select('a[href*=".com/el"]')from bs4.element import Tagdef default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if not child.has_attr('href'): continue yield childtags = soup.find('body').select("a", _candidate_generator=default_candidate_generator)print(type(tags), tags)from bs4.element import Tagdef default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if not child.has_attr('href'): continue yield childtags = soup.find('body').select("a", _candidate_generator=default_candidate_generator, limit=1)print(type(tags), tags) |
19. 标签的内容
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# tag = soup.find('span')# print(tag.string) # 获取# tag.string = 'new content' # 设置# print(soup)# tag = soup.find('body')# print(tag.string)# tag.string = 'xxx'# print(soup)# tag = soup.find('body')# v = tag.stripped_strings # 递归内部获取所有标签的文本# print(v) |
20.append在当前标签内部追加一个标签
|
1
2
3
4
5
6
7
8
9
10
|
# tag = soup.find('body')# tag.append(soup.find('a'))# print(soup)## from bs4.element import Tag# obj = Tag(name='i',attrs={'id': 'it'})# obj.string = '我是一个新来的'# tag = soup.find('body')# tag.append(obj)# print(soup) |
21.insert在当前标签内部指定位置插入一个标签
|
1
2
3
4
5
6
|
# from bs4.element import Tag# obj = Tag(name='i', attrs={'id': 'it'})# obj.string = '我是一个新来的'# tag = soup.find('body')# tag.insert(2, obj)# print(soup) |
22. insert_after,insert_before 在当前标签后面或前面插入
|
1
2
3
4
5
6
7
|
# from bs4.element import Tag# obj = Tag(name='i', attrs={'id': 'it'})# obj.string = '我是一个新来的'# tag = soup.find('body')# # tag.insert_before(obj)# tag.insert_after(obj)# print(soup) |
23. replace_with 在当前标签替换为指定标签
|
1
2
3
4
5
6
|
# from bs4.element import Tag# obj = Tag(name='i', attrs={'id': 'it'})# obj.string = '我是一个新来的'# tag = soup.find('div')# tag.replace_with(obj)# print(soup) |
24. 创建标签之间的关系
|
1
2
3
4
|
# tag = soup.find('div')# a = soup.find('a')# tag.setup(previous_sibling=a)# print(tag.previous_sibling) |
25. wrap,将指定标签把当前标签包裹起来
|
1
2
3
4
5
6
7
8
9
10
11
|
# from bs4.element import Tag# obj1 = Tag(name='div', attrs={'id': 'it'})# obj1.string = '我是一个新来的'## tag = soup.find('a')# v = tag.wrap(obj1)# print(soup)# tag = soup.find('a')# v = tag.wrap(soup.find('p'))# print(soup) |
26. unwrap,去掉当前标签,将保留其包裹的标签
|
1
2
3
|
# tag = soup.find('a')# v = tag.unwrap()# print(soup) |
更多参数官方:http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/

浙公网安备 33010602011771号