requests bs4 xpath

1 安装

pip install requests

2 requests发送get请求

import requests

header = {
	'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
	'referer': 'https://www.baidu.com'  # 用来标记从那个页面来的
}
res = requests.get('https://www.baidu.com', header=header)
res.text  # 获取到的页面
res.content  # 二进制内容

3 请求携带参数

res=requests.get('https://www.baidu.com/s',headers=header,params={'wd':'hellow'})

4 请求带cookie(两种方式)

# 方式一,在header中放
header = {
	'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
	'cookie': 'key=asdfasdfasdfsdfsaasdf;key2=asdfasdf;key3=asdfasdf'
}
res = requests.get('http://127.0.0.1:8000/index/', headers=header)



# 方式二:
header = {
	'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
}
# cookies是一个字典或者CookieJar对象
res = requests.get('http://127.0.0.1:8000/index/', headers=header, cookies={'key': 'asdfasdf'})

5 发送post请求

5.1 发送post请求,携带数据(urlencoded和json)

res=requests.post('http://127.0.0.1:8000/index/',data={'name':'lqz'})
print(res.text)

res=requests.post('http://127.0.0.1:8000/index/',json={'age':1,},)
print(res.text)

5.2 自动携带cookie

session=requests.session()
res=session.post('http://127.0.0.1:8000/index/')  # 假设这个请求登录了
res1=session.get('http://127.0.0.1:8000/order/')  # 现在不需要手动带cookie,session会帮咱处理

6 response对象

respone=requests.post('http://127.0.0.1:8000/index/',data={'name':'lqz'})
print(respone.text)  # 响应的文本
print(respone.content)  # 响应体的二进制


print(respone.status_code)  # 响应状态码
print(respone.headers)    # 响应头
print(respone.cookies)   # cookie
print(respone.cookies.get_dict()) #  把cookie转成字典
print(respone.cookies.items())  # key和value

print(respone.url)        # 请求的url
print(respone.history)   #[]放重定向之前的地址

print(respone.encoding)  # 响应的编码方式

respone.iter_content()  # 图片,视频,大文件,一点一点循环取出来
for line in respone.iter_content():
	f.write(line)

7 解析返回的json数据

import json
respone=requests.post('http://127.0.0.1:8000/index/',data={'name':'lqz'})
print(type(respone.text))  # 响应的文本
print(json.loads(respone.text))
print(respone.json())  # 相当于上面那句话

8 携带证书

import requests
respone=requests.get('https://www.12306.cn') #不验证证书,报警告,返回200
print(respone.status_code)
# 使用证书,需要手动携带

import requests
respone=requests.get('https://www.12306.cn',
					 cert=('/path/server.crt',
						   '/path/key'))
print(respone.status_code)

9 上传文件

res=requests.post('http://127.0.0.1:8000/index/',files={'myfile':open('a.jpg','rb')})
print(res.text)

10 代理池的搭建

秉持着有轮子绝不早的原则,我们使用别人搭建好的
github:https://github.com/jhao104/proxy_pool

11 bs4的使用

11.1 下载

pip install beautifulsoup4
pip install lxml  # 解析器

11.2 实例化

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my_p" class="title">hello<b id="bbb" class="boldest">The Dormouse's story</b>
</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a><a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
# 文档容错能力,不是一个标准的html也能解析
soup=BeautifulSoup(html_doc,'lxml')

11.3 获取标签

# 1 遍历文档树:即直接通过标签名字选择,特点是选择速度快,但如果存在多个相同的标签则只返回第一个

head = soup.head
print(head.name)  # 获取标签的名称

# 获取标签的属性(重点) class可能有多个,即便有一个也放到列表中
p = soup.body.p
# print(p.attrs)
print(p.attrs.get('class'))
print(p['class'])
print(p.get('class'))

# 获取标签的内容
p = soup.body.p
# text会取该标签,子子孙孙的内容,拼到一起
print(p.text)
print(p.string)  # p下的文本只有一个时,取到,否则为None
print(p.strings)  # 生成器
print(list(p.strings))  # 拿到一个生成器对象, 取到p下所有的文本内容,一个一个的在生成器中

# 嵌套选择
a = soup.body.a
print(a.get('id'))

# 子节点、子孙节点
print(soup.p.contents)  # p下所有子节点
print(soup.p.children)  # 得到一个迭代器,包含p下所有子节点
print(list(soup.p.children))  # 得到一个迭代器,包含p下所有子节点

# 父节点、祖先节点
print(soup.a.parent)  # 获取a标签的父节点(只有一个)
print(soup.p.parent)  # 获取p标签的父节点
print(soup.a.parents)  # 找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
print(list(soup.a.parents))  # 找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
print(len(list(soup.a.parents)))  # 找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
# 兄弟节点
print(soup.a.next_sibling)  # 下一个兄弟
print(soup.a.previous_sibling)  # 上一个兄弟

print(list(soup.a.next_siblings))  # 下面的兄弟们=>生成器对象
print(list(soup.a.previous_siblings))  # 上面的兄弟们=>生成器对象









# 2 搜索文档树

find()  # 只返回找到的第一个
find_all()  # 找到的所有

# 五种过滤器: 字符串、正则表达式、列表、True、方法

# 字符串过滤,过滤内容是字符串
a = soup.find(name='a')
res = soup.find(id='my_p')
res = soup.find(class_='story')
res = soup.find(href='http://example.com/elsie')

res = soup.find(attrs={'id': 'my_p'})
res = soup.find(attrs={'class': 'story'})
print(res)

# 正则表达式
import re

re_b = re.compile('^b')
res = soup.find(name=re_b)
res = soup.find_all(name=re_b)
res = soup.find_all(id=re.compile('^l'))
print(res)

# 列表
res = soup.find_all(name=['body', 'b'])
res = soup.find_all(class_=['sister', 'title'])
print(res)

# True和false
res = soup.find_all(name=True)
res = soup.find_all(id=True)
res = soup.find_all(id=False)
res = soup.find_all(href=True)
print(res)


# 方法
def has_class_but_no_id(tag):
	return tag.has_attr('class') and not tag.has_attr('id')


print(soup.find_all(has_class_but_no_id))

# limit(限制查找的条数)
res = soup.find_all(name=True, limit=1)
print(res)

# recursive(recursive递归查找,找子子孙孙)
res = soup.body.find_all(name='b ', recursive=False)
res = soup.body.find_all(name='p', recursive=False)
res = soup.body.find_all(name='b', recursive=True)
print(res)

# css选择
ret = soup.select('#my_p')
https: // www.w3school.com.cn / cssref / css_selectors.asp
ret = soup.select('body p')  # 子子孙孙
ret = soup.select('body>p')  # 直接子节点(儿子)
ret = soup.select('body>p')[0].text  # 直接子节点(儿子)
ret = soup.select('body>p')[0].a.find()
print(ret)

12 xpath的使用

12.1 实例化

doc='''
<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html' aa='bb'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html' class='li li-item' name='items'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
   <a href='image6.html' name='items'><span><h5>test</h5></span>Name: My image 6 <br /><img src='image6_thumb.jpg' /></a>
  </div>
 </body>
</html>
'''
from lxml import etree

html=etree.HTML(doc)

12.2 查找标签

# / :从根节点选取。
# // :不管位置,直接找
# /@属性名
# /text()


# 1 属性匹配
a=html.xpath('//body//a[@href="image1.html"]')

# 2 文本获取(重要)  /text() 取当前标签的文本
a=html.xpath('//body//a[@href="image1.html"]/text()')

# 3 属性获取  @href 取当前标签的属性
a=html.xpath('//body//a/@href')

# 4 某一环节获取一个,注意从1 开始取(不是从0)
a=html.xpath('//body//a[1]/@href')

# 5 属性多值匹配
# a 标签有多个class类,直接匹配就不可以了,需要用contains
a=html.xpath('//body//a[@class="li"]')
a=html.xpath('//body//a[contains(@class,"li")]')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 6 多属性匹配
a=html.xpath('//body//a[contains(@class,"li") or @name="items"]')
a=html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()')
a=html.xpath('//body//a[contains(@class,"li")]/text()')

# 7 按序选择
# 取最后一个
a=html.xpath('//a[last()]/@href')

# 位置小于3的
a=html.xpath('//a[position()<3]/@href')

# 倒数第二个
a=html.xpath('//a[last()-2]/@href')

# 8 节点轴选择
# ancestor:祖先节点
# 使用了* 获取所有祖先节点
a=html.xpath('//a/ancestor::*')

# 获取祖先节点中的div
a=html.xpath('//a/ancestor::div')

# attribute:属性值
a=html.xpath('//a[1]/attribute::*')
a=html.xpath('//a[1]/@aa')

# child:直接子节点
a=html.xpath('//a[1]/child::*')
a=html.xpath('//a[1]/child::img/@src')

# descendant:所有子孙节点
a=html.xpath('//a[6]/descendant::*')
a=html.xpath('//a[6]/descendant::h5/text()')

# following:当前节点之后所有节点(兄弟节点和兄弟内部的节点)
a=html.xpath('//a[1]/following::*')
a=html.xpath('//a[1]/following::*[1]/@href')

# following-sibling:当前节点之后同级节点(只找兄弟)
a=html.xpath('//a[1]/following-sibling::*')
a=html.xpath('//a[1]/following-sibling::a')
a=html.xpath('//a[1]/following-sibling::*[2]')
a=html.xpath('//a[1]/following-sibling::*[2]/@href')
posted @ 2022-08-13 22:54  mress  阅读(43)  评论(0)    收藏  举报