bs4解析
通过html标签获取到内容
安装bs4: pip install bs4
语法
1.把页面源代码交给BeautifulSoup进行处理,生产bs对象。
page = BeautifulSoup(resp.text,“html.parser”) #指定html解析器
2.从bs对象中查找数据
find(标签,属性=值)
find_all(标签,属性=值)
例子:
import requests
import re
import csv
from bs4 import BeautifulSoup
url = "官网"
resp = requests.get(url)
resp.encoding = resp.apparent_encoding
#解析数据
# 1.把页面源代码交给BeautifulSoup处理,生产bs对象
page = BeautifulSoup(resp.text,"html.parser") #html.parser表示使用HTML解析器
resp.close()
#2.从bs对象中找数据
# find(标签,属性=值),即只找第一个
# find_all(标签,属性=值)
# table = page.find("table",class_="kj_tablelist01") #class是python的关键字,冲突了,所以需要class_
table = page.find("table",attrs={"class":"kj_tablelist01"}) #class是python的关键字,冲突了,可以用字典存
f = open("balls.csv",mode='w',encoding='utf-8',newline="")
csvwriter = csv.writer(f)
trs = table.find_all("tr")[2:] #切片
for tr in trs:
tds = tr.find_all("td")
ball = []
for td in tds:
td = re.sub("[a-zA-Z()'; \r]", '', td.text).replace("\n","").replace("\t","")
ball.append(td)
scripts = td.find_all("script")
# print(td)
for script in scripts:
script = re.sub("[a-zA-Z()'; \r]",'',script.text).replace("\n","").replace("\t","")
ball.append(script)
# print(script)
while '' in ball:
ball.remove('')
csvwriter.writerow(ball)
f.close()
例子:爬取下载壁纸
import time
import requests
from bs4 import BeautifulSoup
url = "壁纸网页地址"
resp = requests.get(url)
resp.encoding = resp.apparent_encoding
domain = "官网地址"
#解析数据
# 1.把页面源代码交给BeautifulSoup处理,生产bs对象
page = BeautifulSoup(resp.text,"html.parser") #html.parser表示使用HTML解析器
resp.close()
aList = page.find_all("a",attrs={"class":"imgTitle"})
for a in aList:
href = a.get("href")
respChild = requests.get(domain+href)
respChild.encoding = "utf-8"
pageChild = BeautifulSoup(respChild.text,"html.parser")
respChild.close()
imgList = pageChild.find_all("img",attrs={"class":"lazy"})
for img in imgList:
src = img.get("src")
src = "http:"+src
imgName = src.split("/")[-1] #用/进行分片,取最后一段
# 下载图片
imgResp = requests.get(src)
with open("img/"+imgName,mode="wb") as f:
f.write(imgResp.content)#取字节,写入文件
f.close()
time.sleep(2)