BeautifulSoap库
request库(内含高级库)
代码展示:
import requests
from bs4 import BeautifulSoup
import re
import os
url = "https://www.jianshu.com/"
headers1 = {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"
}
req = requests.get(url, headers=headers1)
print(req.status_code) # 请求状态
req.text # 响应html
print(req.encoding) # 默认编码(可修改)
req.content # http相应内容的二进制形式,可用于保存爬取的图片,视频等
req.raise_for_status() # 如果状态码不是200,产生异常requests.HTTPError,结合try..,except..使用
# 对象soup是对html的解析,我们可以对它的内容进行更改
# Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象
soup = BeautifulSoup(req.text, "html.parser")
# print(connect.find_all('a'))
soup.a.parent.name # 获取第一个标签<a></a>的父节点
soup.a.string # 标签a的内容, 如果tag包含了多个子节点,tag就无法确定 .string 方法应该调用哪个子节点的内容, .string 的输出结果是 None
# 输出的字符串中可能包含了很多空格或空行,使用 .stripped_strings 可以去除多余空白内容
soup.get_text() # html的所有文字内容
# .contents 和 .children 属性仅包含tag的直接子节点;.descendants 属性可以对所有tag的子孙节点进行递归循环
# .parent和.parents,一个父节点,遍历所有父节点在
# 文档树中,使用 .next_sibling(下一个) 和 .previous_sibling(上一个) 属性来查询兄弟节点,经常得到的是‘\n’,在。next_sibling即可;.next_siblings 和 .previous_siblings遍历所有兄弟节点
# 引入正则
soup.find_all(string=re.compile("sisters")) # 获取包含‘sisters’tag的文字内容
for tag in soup.find_all(re.compile("^b")): # 匹配所有包含‘b’字母的tag
pass
soup.find_all(href=re.compile("elsie")) # 传入 href 参数,Beautiful Soup会搜索每个tag的”href”属性是包含elsie
# find_all( name , attrs , recursive , string , **kwargs )
# name参数可以是字符串,正则表达式,列表,方法或是true
# keyword参数,一般作为tag的属性查找
# 有些tad属性不能被搜索时,是使用attrs参数如:data_soup.find_all(attrs={"data-foo": "value"}),注:data-foo是tag的属性,value是data-foo的值
for href in soup.find_all('a', target="_blank", class_='title'): # 寻找所有具有还属性的标签,注意class属性不能直接用class,需要用class_
href # 循环节点的某一条标签
print(href.get('href')) # 获取该标签属性的内容
print(href['href']) # 同上,获取该标签属性的内容
print(href.text) # 获取标签的内容
# tag的属性可以被添加,删除或修改. 再说一次, tag的属性操作方法与字典一样
soup.find_all("a", limit=2) # 添加limit参数,只返回两个a标签
# 下面两行代码是等价的
soup.title.find_all(string=True)
soup.title(string=True)
# print(href)