一、bs4解析
首先:bs4安装:pip install bs4
使用bs4爬取数据步骤:
1.拿到页面源代码
2.使用bs4进行解析,拿到数据
解析数据
1.把页面源代码交给BeautifulSoup进行处理,生成bs对象
2.从bs对象中查找数据:find(标签,属性=值), find_all(标签,属性=值)
page.find(“table”, class_=“hq_table”) # class是python的关键字,加上_则不为关键字
举例:1.搞搞菜价
import requests
from bs4 import BeautifulSoup
import csv
url = "http://www.xinfadi.com.cn/marketanalysis/0/list/1.shtml"
resp = requests.get(url)
f = open("菜价.csv", mode="w",encoding="utf-8")
cswriter = csv.writer(f)
# 解析数据
# 1.把页面源代码交给BeautifulSoup进行处理,生成bs对象
page = BeautifulSoup(resp.text, 'html.parser') # 指定html解析器
# 2.从bs对象中查找数据:find(标签,属性=值), find_all(标签,属性=值)
# page.find("table", class_="hq_table") # class是python的关键字,加上_则不为关键字
table = page.find("table", attrs={"class": "hq_table"}) # 与上一行一致
# 拿到所有数据行
trs = table.findAll("tr")[1:]
for tr in trs:
tds = tr.find_all("td") # 拿到每一行中的所有td
name = tds[0].text # 表示拿到被标签标记的内容
low = tds[1].text
avg = tds[2].text
high = tds[3].text
gui = tds[4].text
kind = tds[5].text
date = tds[6].text
cswriter.writerow([name,low,avg,high,gui,kind,date])
f.close()
resp.close()
print("over!!")
所得csv文件:
举例:2.爬取优美图片
步骤:
1.拿到主页面的源代码,然后提取到子页面的链接地址,href
2.通过href拿到子页面的内容,从子页面中找到图片的下载地址 img–>src
3.下载图片
import time
import requests
from bs4 import BeautifulSoup
url = "https://www.umei.net/weimeitupian/"
resp = requests.get(url)
resp.encoding = 'utf-8' # 处理乱码
# print(resp.text)
# 把源代码交给bs
main_page = BeautifulSoup(resp.text, 'html.parser')
aList = main_page.find("div", class_="TypeList").find_all("a")
for it in aList:
href = 'https://www.umei.net/'+it.get('href') # 直接根据get拿到属性的值
# print(href)
# 拿到子页面的源代码
child_page_resp = requests.get(href)
child_page_resp.encoding = 'utf-8'
# 从子页面中拿到图片的下载路径
child_page = BeautifulSoup(child_page_resp.text, 'html.parser')
p = child_page.find("p", align="center")
img = p.find("img")
src = img.get("src")
# 下载图片
img_resp = requests.get(src)
img_name = src.split("/")[-1] # 拿到url中的最后一个/以后的内容
with open("img00/"+img_name,mode="wb") as f:
f.write(img_resp.content) # 这里拿到的img_resp.content 是字节 将图片写入文件
print("over!")
time.sleep(1)
print("all over!")
resp.close()
所得图片文件:
二、xpath解析
1.xpath 是XML文档中搜索内容的一门语言
2.html是xml的一个子集
3.安装lxml模块 pip install lxml
举例:1.从自定义xml文件中提取内容
from lxml import etree # etree.XML().xpath()
xml = """
<book>
<id>1</id>
<name>野花遍地开</name>
<price>1.23</price>
<nick>臭豆腐</nick>
<author>
<nick id="10086">周杰伦</nick>
<nick id="10010">周芷若</nick>
<nick class="joy">周大强</nick>
<nick class="jolin">蔡依林</nick>
<div>
<nick>啦啦啦啦啦1</nick>
</div>
<div>
<nick>啦啦啦啦啦2</nick>
</div>
</author>
<partner>
<nick id="ppc">胖胖陈</nick>
<nick id="ppbc">胖胖不陈</nick>
</partner>
</book>
"""
tree = etree.XML(xml)
# result = tree.xpath("/book") # /表示层级关系,第一个/是根节点
# result = tree.xpath("/book/name/text()")
# tree.xpath("/book") 从文件中提取括号里对应内容
result = tree.xpath("/book/author/nick/text()") # text() 是拿文本
result1 = tree.xpath("/book/author//nick/text()") # //表示后代
result2 = tree.xpath("/book/author/*/nick/text()") # * 表示任意的节点,同配符
print(result2)
举例:2.从html文件中解析提取内容
THML文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Title</title>
</head>
<body>
<ul>
<li><a href="https://www.baidu.com/">百度</a></li>
<li><a href="https://www.google.com/">谷歌</a></li>
<li><a href="https://www.sogou.com/">搜狗</a></li>
</ul>
<ol>
<li><a href="feiji">飞机</a></li>
<li><a href="dapao">大炮</a></li>
<li><a href="huoche">火车</a></li>
</ol>
<div class="job">李嘉诚</div>
<div class="common">胡辣汤</div>
</body>
</html>
from lxml import etree
tree = etree.parse("b.html") # 直接加载html文件
result = tree.xpath("/html/body/ul/li[1]/a/text()") # /li[1] 表示拿ul下的第一个li标签内容
# xpath索引顺序是从1开始的
result1 = tree.xpath("/html/body/ol/li/a[@href='dapao']/text()")
# a[@href='dapao'] 表示从li标签下找到属性为'dapao'的对应标签 [@XXX=XXX] 是属性的筛选
ol_li_List = tree.xpath("/html/body/ol/li") # 得到的是ol标签下所有的li标签
for li in ol_li_List:
# 从每一个li中提取文字信息
result2 = li.xpath("./a/text()") # 在li中继续寻找,相对查找 其中./表示当前标签下
result3 = li.xpath("./a/@href") # 拿到属性值:@属性
print(result3)
print(result1)
print(tree.xpath("/html/body/div[1]"))
举例:3. 爬取猪八戒网信息
步骤:
1.拿到页面源代码
2.提取和解析数据
import requests
from lxml import etree
url = "https://ganzhou.zbj.com/search/f/?type=new&kw=saas"
resp = requests.get(url)
# 解析
html = etree.HTML(resp.text) # etree.HTML(resp.text)表示加载html源码
# 拿到每一个服务商的div
divs = html.xpath("/html/body/div[6]/div/div/div[2]/div[6]/div[1]/div")
for i in divs: # 每一个服务商信息
price = i.xpath('./div/div/a[1]/div[2]/div[1]/span[1]/text()')
title = "saas".join(i.xpath('./div/div/a[1]/div[2]/div[2]/p/text()'))
com_name = i.xpath('./div/div/a[2]/div[1]/p/text()')
location = i.xpath('./div/div/a[2]/div[1]/div/span/text()')
print(com_name)
resp.close()
所得运行结果: