1.1借助Chrome开发者工具来分析页面
User-Agent:自己电脑浏览器版本等信息
cookie:登录之后才能看的信息,必须学会操作cookie
Headers 是我们发起请求时给服务器发送的消息,服务器通过此处判断我们的身份。
1.2编码规范
def main():
print("hello")
#main()
if __main__=="__main__": #当程序执行时,能够让调用按照自己顺序来,更清晰,为程序入口
#调用函数
main()
1.3引入库
#引入自定义模块 from 文件夹/包 from 模块 #引入系统级 import sys import os #引入第三方模块 import re
安装库
1)在Local处使用pip 库名,必须要保证联网,不然断掉就失败了
2)file——settings——project 本项目名——project interpreter——可以删除添加
import bs4 #网页解析,获取数据 import re #正则表达式,进行文字匹配 import urllib.request,urllib.error #制定URL,获取网页数据 import xlwt #进行excel操作 import sqlite3 #进行SQLite数据库操作2.获取数据
python一般使用urllib库获取页面
urllib库
import urllib.request
#获取一个get请求
response=urllib.request.urlopen("http://www.baidu.com")
print(response.read()decode('utf-8')) #读取response对象的内容,response放的是源码,可以使用decode来解码,防止乱码,添加格式正常显示
#获取一个post请求,一般用来模拟用户登陆的情况
#表单信息
import urllib.parse #解析器,不管中英文 按照某种格式来解析
data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8") #bytes是变成字节文件,来封装所需要的参数
response=urllib.request.urlopen("http://httpbin.org/post",data=data)
print(response.read().decode("utf-8"))
#限时,超时报错,可以使用try except来处理异常
try:
response=urllib.request.urlopen("http://httpbin.org/get",timeout=0.1)
print(response.read().decode("utf-8"))
except urllib.error.URLError as e:
print("time out!")
补充:可以在httpbin.org网站进行测试
状态码
response=urllib.request.urlopen("http://www.baidu.com")
print(response.status) ##状态码
print(response.getheaders()) #响应头
print(response.getheader("Server"))
状态码
1 表示消息
2 表示成功
3 表示重定向
4 表示请求错误,418发现你是爬虫了
5 表示服务器错误
被识别了,需要伪装成浏览器
url="http://httpbin.org/post"
#伪装response body user-Agent尤为重要,可以在网页network,将进程停止,固定,在headers中找到user-agent,复制作为头部信息,想伪装更多可以加其他信息
header={"User-Agent":"复制的user-agent"}
data=bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
req=urllib.request.Request(url=url,data=data,headers=headers,method="POST"
) #加强版的请求,可删减
response= urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
访问豆瓣
url="http://www.duban.com"
#伪装response body user-Agent尤为重要,可以在网页network,将进程停止,固定,在headers中找到user-agent,复制作为头部信息,想伪装更多可以加其他信息
header={"User-Agent":"复制的user-agent"}
req=urllib.request.Request(url=url,data=data,headers=headers) #加强版的请求,可删减
response= urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
BeautifulSoup
Beautifulsoup4将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4中:解析网页,html,json等,提取所想要的
**Tag:print(a)打印标签及其内容,,
NavigableString:标签里的内容
BeautifulSoup:整个文档
Comment: 特殊的NavigableString,输入的内容不包含注释符号
**
from bs4 import BeautifulSoup
file=open("./baidu.html","rb")
html=file.read()
bs=BeautifulSoup(html,"html.parser")
print(bs.title)#打印出百度一下,你就知道,打印出的是找到的页面第一个符合的
print(bs.title.string)#打印出 百度一下,你就知道
print(bs.a.attrs)#打印出 标签里面其他的属性,以 键值对显示,{‘class’:['mnav'],'href':'htttp://news.baidu.com','name':'tj_trnews'}
print(type(bs))#
print(bs)#整个文档
print(bs.a.string)
#文档的遍历 print(bs.head.contents)#打印出了head中的内容 print(bs.head.contents[1])#可以用下标显示 #更多内容可以搜索文档
#文档的搜索
1.find_all()查找所有:字符串过滤:会查找与字符串完全匹配的内容
t_list=bs.find_all("a")
print(t_list)
#正则表达式搜索:search()方法来匹配内容
import re
t_list=bs.find_all(re.compile("a"))#只要标签中含有a,就把标签和内容都找出来
#方法:传入一个函数(方法),根据函数的要求搜索
def name_is_exists(tag)
return tag.has_attr("name")
t_list=bs.find_all(name_is_exists)
2.kwargs 参数
t_list=bs.find_all(id="head") t_list=bs.find_all(class=True) for item in t_list: print(item)
3.text 参数
t_list=bs.find_all(text="123")
t_list=bs.find_all(text=["123","地图","贴吧"])
t_list=bs.find_all(text=re.compile("d")) #应用正则表达式来查找指定文本的内容,(标签里面的字符串)
for item in t_list:
print(item)
4.limit 参数,限制条数
t_list=bs.find_all("a",limit=3)
for item in t_list:
print(item)
css选择器
t_list=bs.select('title')#通过标签来查找
t_list=bs.select('.mnav')#通过类名来查找
t_list=bs.select('#u1')#通过id来查找
t_list=bs.select('a[class='bri']')#通过属性来查找
t_list=bs.select("head > title")#通过子标签来查找
t_list=bs.select(".mnav~ .bri") #通过mnav下面的.bri来查找
print(t_list[0].get_text())#get_text拿到文本
for item in t_list:
print(item)



