爬虫学习2
数据解析
正则表达式
量词:
import re
#searcch只会匹配到第一次匹配的内容
#result = re.search(r"\d+","今年32")
#print(result.group())
#result = re.findall(r"\d+","我是一个abcdeafg")
#print(result)
#search只会匹配到第一次匹配的内容
#result = re.finditer(r"\d+","我是18岁,我有20000000000000000000块")
#for item in result:#从迭代器中拿内容
# print(item.group())
#match在匹配的时候,是从字符串的开头进行匹配的,类似这正则前面加上了^
#result = re.match(r"\d+","我叫周杰伦","今年32岁,我的班级是5年4班")
#print(result)
#预加载,提前把正则对象加载完毕
#obj = re.compile(r"\d+")
#result = obj.findall("我叫周杰伦,今年32岁,我的班级是5年纪4班")
#print(result)
#想要提取数据必须小括号括起来,可以单独起名字
#(?P<名字>正则)
#提取数据的时候,需要group("名字")
s = """
<div class= '西游记'><span id='10010'>中国联通</span></div>
<div class= '西游记'><span id='10010'>中国移动</span></div>
"""
obj = re.compile(r"<span id='(?P<haha>\d+)'>(?P<name>.*?)</span")
result = obj.finditer(s)
for item in result:
id = item.group("haha")
print(id)
name = item.group("name")
print(name)
#1.拿到页面源代码
#2.编写正则,提取页面数据
#3.保存数据
import requests
import re
url = "https://movie.douban.com/chart"
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
}
resp = requests.get(url,headers=headers)
#resp.encodeing = 'utf-8'#解决乱码问题
pageSource = resp.text
#print(pageSource)
#编写正则表达式
#re.s可以让正则中的.匹配换行符
obj = re.compile(r'<div class="item">.*?<span class="title">(?P<name>.*?)</span>',re.S)
#进行正则匹配
result = obj.finditer(pageSource)
for item in result:
print(item.group("name"))#那结果
from lxml import etree
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>惹了</nick>
</div>
</author>
<partner>
<nick id="ppc'>胖胖陈</nick>
<nick id="ppbc">胖胖不陈</nick>
</partner>
</book>
"""
#此时练习只能用XMLxml
et = etree.XML(xml)
result = et.xpath("/book") #/表示根节点
result = et.xpath("/book/name") # 在xpath中间的/表示的是儿子#
result = et.xpath("/book/name/text()")[0]# text()拿文本并result = et.xpath("/book//nick") # //表示的是子孙后代#
result = et.xpath("/book/*/nick/text()") #* 通配符,谁都行
result = et.xpath("/book/author/nick[@class='jay']/text()")
result = et.xpath("/book/partner/nick/@id")#
print(result)
#此时练习只能用xml