版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
项目3项目网页数据解析与抓取——抓取电影网站的数据任务3.1正则表达式及其应用3.1.1
正则表达式介绍正则表达式(RegularExpression,简称regex或regexp)又称规则表达式,是对字符串操作的一种逻辑公式。
通俗来讲,正则表达式就像一种高级搜索语言,它不只是简单查找某个词,更像是给计算机下了一个精确的操作指令,让计算机自动帮你找到符合规则的信息。举例如下。查找以字母开头、后面跟着6个数字的内容。查找手机号码格式的内容,查找网页中的所有邮箱地址。3.1.1
正则表达式介绍表3-1所示为常见的正则表达式规则及功能。正则表达式功
能\d表示一个数字*表示任意字符[]方括号内的字符只能取其一{}指定字符的个数+表示前一个字符至少出现一次—表示一个范围?表示前一个字符可出现零次或一次.匹配除换行符以外的任意字符|分支结构,匹配符号之前的字符或之后的字符\转义符^匹配行的开始$匹配行的结束3.1.1
正则表达式介绍例如,声明“电话号码”这一匹配规则。该格式由“***-********”组成,如,可使用正则表达式书写为\d{3}-\d{8}。但为了确保精确匹配整个字符串(避免匹配到更长字符串中的部分内容),建议加上开始^和结束$边界符,最终表达式为^\d{3}-\d{8}$。该表达式的含义如下:
^:字符串开始\d{3}:匹配3个数字-:匹配一个连字符\d{8}:匹配8个数字$:字符串结束匹配成功:023-676700113.1.2
正则表达式应用
1.认识re模块在Python中,re是一个用于处理正则表达式的内置模块。它提供了强大的字符串匹配、搜索和替换功能,广泛应用于文本处理、数据验证、爬虫开发等领域。re模块的使用语法如下:
importre2.掌握re模块【例3-1】使用search()函数匹配普通字符串。
importre#导入模块a="student"str1="teacherandstudent"ret=re.search(a,str1)print(ret)3.1.2
正则表达式应用
【例3-2】使用通用字符串匹配字符。
importrea="\d{2}st"str1="teacherand12345student"ret=re.search(a,str1)print(ret)
在该示例中,\d{2}st表示在字符st前面有2个任意的十进制数字0~9,运行结果如图3-2所示。3.1.2
正则表达式应用【例3-3】使用re.match()函数进行匹配。
importreprint(re.match('xyz','')) #在起始位置匹配
print(re.match('xyz','')) #不在起始位置匹配
运行结果如图3-3所示。3.1.2
正则表达式应用
【例3-4】使用re.findall()函数进行匹配。
importreprint(re.findall(r'123','123python123')) #匹配成功
print(re.findall(r'123py','123python123')) #匹配成功
print(re.findall(r'1234','123python123')) #匹配不成功
运行结果如图3-4所示。3.1.2
正则表达式应用
【例3-5】使用re.findall匹配数字。
importrepatt=r'[1-5][0-9]'lis=[10,20,30,40,2,3,59,60,'aa','3aaa']match=re.findall(patt,str(lis))ifmatch:print(match)
运行结果如图3-5所示。3.1.2
正则表达式应用
【例3-6】使用re.findite()函数遍历所有匹配项。
importre#示例文本text="联系方式备用号码#正则表达式:匹式的电话号码pattern=r'\d{3}-\d{8}'#遍历所有匹配项formatchinre.finditer(pattern,text):print(f"找到:{match.group()},位置:{match.start()}")
运行结果如图3-6所示。3.1.2
正则表达式应用
【例3-7】使用pile()函数编译表达式。
importre#编译正则表达式phone_pattern=pile(r'1[3-9]\d{9}')#要搜索的文本text="我的电话备用号码还有个无效号码12345678901"#查找所有匹配的手机号phones=phone_pattern.findall(text)print("找到的手机号:",phones)
运行结果如图3-7所示。3.1.2
正则表达式应用
【例3-8】使用正则表达式提取<a>
标签的
href
属性值。
importrehtml='''<ahref="">Example</a><ahref=''>百度</a><ahref=>Test</a>'''#正则表达式:匹配href属性值(支持单引号、双引号、无引号)pattern=r'href\s*=\s*["\']?([^"\'>]+)["\']?'urls=re.findall(pattern,html)print(urls)
运行结果如图3-8所示。3.应用re模块3.1.2
正则表达式应用
【例3-9】使用正则表达式提取特定class的<div>标签内容。
importrehtml='''<divclass="content">这是第一段内容</div><divclass="footer">不感兴趣的内容</div><divclass="content">这是第二段内容</div>'''#正则表达式:匹配class="content"的<div>标签内容(非贪婪模式)pattern=r'<div[^>]+class="content"[^>]*>(.*?)</div>'results=re.findall(pattern,html,re.DOTALL)forresultinresults:print(result.strip())3.应用re模块3.1.2
正则表达式应用
【例3-10】使用正则表达式提取HTML文本中的特定数据。
importrecontent='''<ahref="">新闻</a><ahref="">hao123</a><ahref="">地图</a>'''res=r"(?<=href=\").+?(?=\")"urls=re.findall(res,content)forurlinurls:print(url)
运行结果如图3-10所示。3.应用re模块3.1.2
正则表达式应用
【例3-11】使用正则表达式查找网页的文本数据。
importrekey="<html><body><h1>helloworld</h1></body></html>" #要查找的文本p=r"<h1>.+</h1>" #正则表达式pattern=pile(p) #对正则表达式进行编译matcher=re.findall(pattern,key) #在文本中进行查找print(matcher)
运行结果如图3-11所示。3.应用re模块任务3.2BeautifulSoup及其应用3.2.1
BeautifulSoup介绍BeautifulSoup是Python中一个非常流行的HTML和XML解析库,特别适合用于从网页中提取数据。它能够将复杂的HTML或XML文档转换为树形结构,并提供了简单的方法来导航、搜索和修改这些结构。BeautifulSoup将复杂的HTML文档转换为一个树形结构来读取,其中树形结构中的每个节点都是Python对象,并且所有对象都可以归纳为Tag、NavigableString、BeautifulSoup及Comment等4种。
BeautifulSoup(根)|├──Tag<divclass="content">│├──Tag<h1id="title">││└──NavigableString"Hello"│└──Comment"这是一个注释"└──...要使用BeautifulSoup,首先需要在Python3中安装,可以直接在cmd下使用pip3命令进行安装:
pipinstallBeautifulSoup4
在Python3中,BeautifulSoup的导入语句如下:
frombs4importBeautifulSoup3.2.2
BeautifulSoup应用【例3-12】使用BeautifulSoup解析HTML文本。
frombs4importBeautifulSouphtml="<divclass='brr'>网页1</div>"soup=BeautifulSoup(html,'html.parser')#解析网页tag=soup.div#tag表示HTML或XML文档中的标签print()print(tag.text)print(tag['class'])print()
该示例使用BeautifulSoup解析HTML文本,并提取标签、文本和属性信息。3.2.2
BeautifulSoup应用【例3-13】使用BeautifulSoup读取本地HTML文件并进行解析。
frombs4importBeautifulSoupfile=open('1-51.html','rb')html=file.read()soup=BeautifulSoup(html,"html.parser") #使用html.parser作为解析器,用于创建BeautifulSoup对象print(soup.prettify()) #打印整个html文件的树形结构print(soup.body) #获取<body>标签的名称print(soup.text)
其中1-51.html文件中的内容如下:
<!DOCTYPEhtml><htmllang="zh"><head><title>这是我的网页</title></head><body><h1>我的第一个标题</h1><div>我喜欢计算机</div><pid='a1'>我的第一个段落</p><pid='a1'>我的第二个段落</p><ahref="">java</a><ahref="">Python</a><ahref="">c++</a></body></html>3.2.2
BeautifulSoup应用【例3-14】查找单个元素h1。
frombs4importBeautifulSouphtml='''<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>'''soup=BeautifulSoup(html,'html.parser')h1=soup.find('h1')print(h1.text)
运行结果如图3-14所示。3.2.2
BeautifulSoup应用【例3-15】查找所有元素p。
frombs4importBeautifulSouphtml='''<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>'''soup=BeautifulSoup(html,'html.parser')paragraphs=soup.find_all('p')forpinparagraphs:print(p.text)
运行结果如图3-15所示。3.2.2
BeautifulSoup应用【例3-16】使用find与find_all查找所有<p>标签。
frombs4importBeautifulSoup
html='''<pclass="intro">这是第一个段落。</p><ahref=""class="link">网页1</a><pid="content"class="main">这是第二个段落,包含重要信息。</p><imgsrc="image.jpg"alt="小猪"><p>这是第三个段落。</p>'''
soup=BeautifulSoup(html,'html.parser')
#查找第一个<p>标签first_p=soup.find('p')print("第一个<p>标签文本:",first_p.get_text())print("class属性:",first_p.get('class'))#输出:['intro']print("id属性:",first_p.get('id'))#输出:None
print("-"*40)
#查找所有<p>标签all_p=soup.find_all('p')print(f"共找到{len(all_p)}个<p>标签")fori,pinenumerate(all_p,1):print(f"第{i}个<p>文本:{p.get_text()}")print(f"class:{p.get('class')}")print(f"id:{p.get('id')}")3.2.2
BeautifulSoup应用【例3-17】使用class属性查找元素。网页内容:
<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>
编写代码:
frombs4importBeautifulSouphtml='''<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>'''soup=BeautifulSoup(html,'html.parser')intro_p=soup.find('p',class_='intro')print(intro_p.text)3.2.2
BeautifulSoup应用【例3-18】使用class选择器查找网页元素。
frombs4importBeautifulSouphtml_string="""<!DOCTYPEhtml><html><head> <title>ExamplePage</title></head><body> <h1>Hello,World!</h1> <pclass="first">Thisisthe<b>first</b>paragraph.</p> <pclass="second">Thisisthe<b>second</b>paragraph.</p> <ahref="">GoWebsite</a> <ahref="">MyWebsite</a> <ahref="">YouWebsite</a> <divclass='link'>oner</div> <divclass='link'>ben</div> <divclass='link1'>today</div></body></html>"""soup=BeautifulSoup(html_string,features="html.parser")p=soup.find('p',{'class':'second'}) #获取class为second的p标签print(p.text)p=soup.find('p',{'class':'first'}) #获取某个标签的父标签#查找所有<p>标签ps=soup.select('p')print(len(ps))#输出:2forpinps:print(p.text)ps1=soup.select_one('p.first') #使用CSS选择器查找标签print(ps1.text)ps2=soup.select_one('p.second') #使用CSS选择器查找标签print(ps2.text)ps3=soup.select_one('div.link1') #使用CSS选择器查找标签print(ps3.text)3.2.2
BeautifulSoup应用【例3-19】使用id属性查找元素。
frombs4importBeautifulSouphtml='''<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>'''soup=BeautifulSoup(html,'html.parser')content_div=soup.find(id='content')print(content_div.p.text)3.2.2
BeautifulSoup应用【例3-20】使用正则表达式匹配元素行。
frombs4importBeautifulSoupimportrehtml='''<html><body><h1>WelcometoBeautifulSoup</h1><pclass="intro">Thisisaparagraph.</p><divid="content"><p>Anotherparagraphinsidediv.</p></div></body></html>'''soup=BeautifulSoup(html,'html.parser')#找出所有class名以intro开头的段落s=soup.find_all('p',class_=pile('^intro'))forpins:print(p.text)3.2.2
BeautifulSoup应用【例3-21】查找元素综合案例。第1步:准备网页2025.html,内容如下。
<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><title>简单示例页面</title></head><body><h1>欢迎来到我的示例页面</h1><pid="intro">这是一个用于演示的简单网页。</p><divclass="content"><h2>文章标题</h2><p>这是文章的第一段内容。</p><p>这是文章的第二段内容。</p></div></body></html>
该示例的目标如下。读取页面内容。使用BeautifulSoup解析HTML。提取页面标题(<h1>)。提取简介(id="intro")。提取文章标题(<h2>)和正文内容(.contentp)。3.2.2
BeautifulSoup应用【例3-21】查找元素综合案例。第1步:准备网页2025.html,内容如下。
<!DOCTYPEhtml><htmllang="zh-CN"><head><metacharset="UTF-8"><title>简单示例页面</title></head><body><h1>欢迎来到我的示例页面</h1><pid="intro">这是一个用于演示的简单网页。</p><divclass="content"><h2>文章标题</h2><p>这是文章的第一段内容。</p><p>这是文章的第二段内容。</p></div></body></html>
该示例的目标如下。读取页面内容。使用BeautifulSoup解析HTML。提取页面标题(<h1>)。提取简介(id="intro")。提取文章标题(<h2>)和正文内容(.contentp)。3.2.2
BeautifulSoup应用第2步:启动Python服务器,将该文件在本地服务器上运行,URL为http://localhost:
8080/2025.html。第3步:编写代码。
importrequestsfrombs4importBeautifulSoup#网页的URLurl='http://localhost:8080/2025.html'#此URL应根据网页实际URL进行替换#发送HTTPGET请求以获取网页内容response=requests.get(url)#检查请求是否成功ifresponse.status_code==200:response.encoding='utf-8'page_content=response.textelse:print(f"无法获取页面内容,状态码:{response.status_code}")exit()#使用BeautifulSoup解析HTMLsoup=BeautifulSoup(page_content,'html.parser')#提取页面标题title=soup.find('h1').textprint(f"页面标题:{title}")#提取简介intro=soup.find(id='intro').textprint(f"简介:{intro}")#提取文章标题article_title=soup.find('h2').textprint(f"文章标题:{article_title}")forparagraphinsoup.select('.contentp'):print(paragraph.text)3.2.3
BeautifulSoup应用
【例3-22】利用find查找网页元素与属性。第1步:准备网页1-52.html,内容如下。
<!DOCTYPEhtml><htmllang="zh"><head><title>这是我的网页</title></head><body><divclass="text-title"><h1>深圳“机器人谷”正在孕育赛道龙头
</h1></div><divid="sohuplayer"><p>深圳“机器人谷”正在孕育赛道龙头</p><p>除此之外,在测试阶段,来自深圳的乐聚夸父机器人以0失误、0换机的表现完成了5公里的奔跑。在正式比赛阶段,乐聚夸父机器人也顺利完赛。</p><p>今天深圳的“机器人天团”早已在各个细分赛道上“奔跑”。中国人形机器人第一股就诞生在深圳,这家人形机器人公司至今仍引领行业发展,将群体智能引入人形机器人领域。</p><p>在这条狭长的谷地中,既有科研机构,也有知名高校,更有著名的机器人公司,形成了产学研一体化的产业集聚特色。</p></div><divclass="statement">平台声明:该文观点仅代表作者本人,搜狐号系信息发布平台,搜狐仅提供信息存储空间服务。</div><divdata-v-140dba88=""class="c-comment-convention"><adata-v-140dba88=""target="_blank"href=
"/s2014/sljyhgy/index.shtml">
搜狐“我来说两句”用户公约</a></div></body></html>2.应用bs4模块第2步:编写代码。
frombs4importBeautifulSoupfile=open('1-52.html','rb')html=file.read()soup=BeautifulSoup(html,"lxml")#lxml的处理速度快,但需要安装e=soup.find("h1")print(e.text)fors2insoup.find_all('p'):print(s2.text)f=soup.find("div",attrs={"class":"statement"})print(f.text)g=soup.find("div",attrs={"class":"c-comment-convention"})print(g.text.strip())【例3-23】利用BeautifulSoup与正则表达式提取网页数据。第1步:网页内容如下。
<divclass="product"><p>Price:$100,Stock:50</p></div>
第2步:编写代码。
frombs4importBeautifulSoupimportrehtml="""<divclass="product"><p>Price:$100,Stock:50</p></div>"""soup=BeautifulSoup(html,'html.parser')text=soup.select_one('.productp').textprice_match=re.search(r'Price:\$(\d+)',text)stock_match=re.search(r'Stock:(\d+)',text)price=price_match.group(1)ifprice_matchelseNonestock=stock_match.group(1)ifstock_matchelseNoneprint(f"Price:{price},Stock:{stock}")
【例3-24】利用BeautifulSoup遍历并提取网页中每种产品的信息。第1步:网页内容如下。
<html><body><divclass="product"><h2>Product1</h2><pclass="price">$10</p></div><divclass="product"><h2>Product2</h2><pclass="price">$20</p></div><divid="footer"><p>Contactusat<ahref="mailto:info@">info@</a></p></div></body></html>frombs4importBeautifulSouphtml="""<html><body><divclass="product"><h2>Product1</h2><pclass="price">$10</p></div><divclass="product"><h2>Product2</h2><pclass="price">$20</p></div><divid="footer"><p>Contactusat<ahref="mailto:info@">info@</a></p></div></body></html>"""soup=BeautifulSoup(html,'html.parser')#使用CSS选择器提取所有class="product"的<div>标签products=soup.select('.product')forproductinproducts:print(product.text.strip())prices=soup.select('.product.price')forpriceinprices:print(price.text)email_link=soup.select_one('#footera[href^="mailto"]')print(email_link['href'])【例3-27】BeautifulSoup解析XML文档。第1步:XML文档内容如下。
<?xmlversion="1.0"encoding="UTF-8"?><movies><movieid="1"><title>肖申克的救赎</title><year>1994</year><director>弗兰克·德拉邦特</director></movie><movieid="2"><title>霸王别姬</title><year>1993</year><director>陈凯歌</director></movie></movies>第2步:编写代码。
frombs4importBeautifulSoup#假设xml_content是从文件或网络获取的XML内容xml_content='''<?xmlversion="1.0"encoding="UTF-8"?><movies><movieid="1"><title>肖申克的救赎</title><year>1994</year><director>弗兰克·德拉邦特</director></movie><movieid="2"><title>霸王别姬</title><year>1993</year><director>陈凯歌</director></movie></movies>'''#使用lxml作为解析器,用于解析XML文档soup=BeautifulSoup(xml_content,'lxml')#查找所有的movie标签movies=soup.find_all('movie')formovieinmovies:title=movie.find('title').textyear=movie.find('year').textdirector=movie.find('director').textprint(f"电影标题:{title},年份:{year},导演:{director}")任务3.3利用Requests和BeautifulSoup爬取新闻网站3.3.2抓取电影网站的数据
首先生成网页,内容如下。
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>电影榜单</title></head><body><divclass="pc_temp_songlist"><ul><li><ahref="/song1">肖申克的救赎</a></li><li><ahref="/song2">阿甘正传</a></li><li><ahref="/song3">霸王别姬</a></li></ul></div><spanclass="pc_temp_num">1</span><spanclass="pc_temp_num">2</span><spanclass="pc_temp_num">3</span><spanclass="pc_temp_tips_r">美国</span><spanclass="pc_temp_tips_r">美国</span><spanclass="pc_temp_tips_r">中国</span><spanclass="pc_temp_te">1994</span><spanclass="pc_temp_te">1994</span><spanclass="pc_temp_te">1993</span></body></html>3.3.2抓取电影网站的数据
代码如下:
frombs4importBeautifulSoup#目标网页html_content='''<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>电影榜单</title></head><body><divclass="pc_temp_songlist"><ul><li><ahref="/song1">肖申克的救赎</a></li><li><ahref="/song2">阿甘正传</a></li><li><ahref="/song3">霸王别姬</a></li></ul></div><spanclass="pc_temp_num">1</span><spanclass="pc_temp_num">2</span><spanclass="pc_temp_num">3</span><spanclass="pc_temp_tips_r">美国</span><spanclass="pc_temp_tips_r">美国</span><spanclass="pc_temp_tips_r">中国</span><spanclass="pc_temp_te">1994</span><spanclass="pc_temp_te">1994</span><spanclass="pc_temp_te">1993</span></body></html>'''headers={'User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/Safari/537.36'}defget_info(html):soup=BeautifulSoup(html,'lxml')ranks=soup.select('span.pc_temp_num')titles=soup.select('div.pc_temp_songlist>ul>li>a')countrys=soup.select('span.pc_temp_tips_r')times=soup.select('span.pc_temp_te')forrank,title,country,timeinzip(ranks,titles,countrys,times):print(f'排名:{rank.get_text(strip=True)}')print(f'电影名:{title.get_text(strip=True)}')print(f'国家:{country.get_text(strip=True)}')print(f'年份:{time.get_text(strip=True)}')print('-'*30)
#直
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 第二节刀具静止角度参考系和刀具静止角度的标注
- No医学科研的特征和类型
- 有机无机化学化工热力学教学课件流体输送
- 纾缓护理的现状与发展
- 湛江市吴川市覃巴镇社区工作者招聘考试题目
- 中国共产党执政历史和人民的选择教学设计
- (2026年)严重群发不良用药事件报告制度
- 学校开学安全隐患排查报告
- 三级安全教育考试试题(附答案)公司级
- 2025年宠物时尚趋势白皮书(上)
- 中等职业学校英语课程标准
- 工地盘扣打包合同协议
- 《作业成本法原理》课件
- 教师培训课件:教师专业成长之我见
- 特种设备之行车、吊装安全操作培训
- 六年级人教版英语单词
- 青年教师成长分享
- HG∕T 3792-2014 交联型氟树脂涂料
- 肺癌的教学查房课件
- 盾构安全培训课件教学
- 2024年福建宁德市城市管理局东侨经济技术开发区分局招考聘用高频考题难、易错点模拟试题(共500题)附带答案详解
评论
0/150
提交评论