当前位置: 首页 > 后端技术 > Python

Python爬虫教程(一)

时间:2023-03-25 23:37:19 Python

Python版本:python3.6使用的工具:pycharm1.第一个爬虫程序获取URL源码。获取百度页面源码如下图。二、Web请求流程1.服务端渲染:直接在服务端整合数据和html返回给浏览器。(数据见页面源码)2.客户端渲染:第一次请求只需要一个html骨架,第二次请求拿到数据进行数据展示。(页面源码中,看不到数据)三、requests入门1、获取搜狗引擎搜索到的周杰伦页面源码。2、出现错误,网页有反爬,处理反爬。3、修改代码,更灵活的获取不同搜索内容对应的不同页面的源代码。4、请求方式为POST时,以百度翻译为例,获取页面源码。5.当你要爬取的数据不在webframe中时。以豆瓣电影排行榜为例。你需要先找到要爬取数据的位置。封装其参数变量,补充URL参数。其参数信息的位置和代码如下:注意:使用爬虫程序后,关闭爬虫程序。上面的例子需要使用resp.close()来关闭爬虫程序。4.数据分析本文将介绍三种分析方法:re分析、bs4分析、xpath分析。1.重新解析:RegularExpression,正则表达式,一种用表达式来匹配字符串的语法规则。Advantages:fastspeed,highefficiency,highaccuracy????Disadvantages:difficulttogetstarted????Grammar:Usemetacharacterstoarrangeandcombinetomatchstrings(metacharactersarespecialsymbolswithfixedmeanings),commonmetacharacters:????.MatchexceptnewlineAnycharacterA|BmatchingcharactersAorB\Wmatchtheletterornumberortheline\wmatchthenon-lettersornumbersortheline\smatchingarbitraryblanksymbol\d数字????[…]匹配字符组中的字符?????????[^…]匹配除字符组中的所有字符????^匹配字符串的开始????????????$匹配字符串的结束????量词:控制元字符出现的次数????*重复零次或多次????+Repeatoneormoretimes?????Repeatzerooronetime????{n}Repeatntimes????{n,}Repeatntimesormore????{n,m}RepeatntomtimesThecontent????(2)finditer()matchesallthecontentsinthestringandreturnstheiteratorThedataneedstouse.group()????(4)match,startmatchingfromthebeginning????Whentheselecteddataistherequireddata,theresultcanbeoutput..We'llwanttoextractthecontentsofthesectiondefiningthegroup(?Pregex),andthenuse.group()toextractthecontentsofacertaingroup.(re.S:Let.beabletomatchnewlinecharacters)????2.ActualcrawlingofDoubanTop250movieinformation.????(1)Userequeststogetthesourcecodeofthepage.(2)Useretoanalyzethedata????andsettocrawltheabovefourdata,moviename,year,rating,numberofreviewers,findtherequiredcontentlocation(redbox)inthepagesourcecode,andfindthecontentpositioningmethodandlocation(whitebox)????parsedata:where.strip()removesthespaceinfrontoftheyear.将获取的文件保存为文件。导入csv并将内容存储在字典中。同样,year需要单独处理。输出文件数据。CSV内容3.实际的战斗爬行电影天堂下载链接,目标是爬网2021必须看到热门电影信息。(1)获取页面源码(2)定位2021必看大热电影,在页面源码中找到所需位置。(3)提取2021必看大热电影子页面链接地址获取的子页面链接不完整,缺少域名,需要拼接。获取完整的子页面链接,保存子页面链接。提取子页面内容,输出标题和下载链接。