python爬虫学习心得记录第一节——爬取网页url和对应的title并存入excel表格
python爬⾍学习⼼得记录第⼀节——爬取⽹页url和对应的title并存⼊excel表格
使⽤pip install 分别安装以下模块
import requests
import cchardet
import bs4
import openpyxl
爬取⽹页源码
定义⼀个函数,需要传⼊要爬取的url进来,这⾥我没有设置异常处理 是不严谨的
def downloader(url,binary=False):
最后的晚餐赏析_headers={
#"Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25", 'User-Agent':('Mozilla/5.0 (compatible; MSIE 9.0; '
好看电视剧推荐'Windows NT 6.1; Win64; x64; Trident/5.0)'),
}
(url,headers=_headers,timeout=10)中国民间传说故事
if binary:
t(url)
else:
encoding=cchardet.t)['encoding']#解析编码格式,⾮⼆进制的,可以拿到⽹页的⽂本部分
t.decode(encoding)#去⽹页乱码的问题
return html
三山五岳指
binary什么情况下设置为true 什么情况下设置为false?
当要下载url指向⼀个图⽚、pdf、word⽂档等,这些都是⼆进制数据,此时要将binary设置为true。直接拿⼆进制数据的话⽤r.content拿数据就可以了。
通过遍历来提炼出url和标题
def getinfo(news,url):
select_a=news.select('a')
if len(select_a)>0:
try:
href=url+select_a[0]['href']
except Exception:
href=''
try:
title=select_a[0]['title']
except Exception:
title=''
# writeintoexcel(i,href, title)
return href,title
母亲节唯美短句使⽤异常处理是为了防⽌爬取中断。
遍历并将数据插⼊excel表
def exewriteinto(alllist,url):
i=2
load = openpyxl.load_workbook('F:\\爬⾍学习\\section1\\1\\新闻爬取.xlsx')    sh = load['Sheet1']
for news in alllist:
href,title=getinfo(news,url)
sh['A'+str(i)].value = href
sh['B'+str(i)].value = title
i = i +1
load.save('F:\\爬⾍学习\\section1\\1\\新闻爬取.xlsx')
main函数部分
if __name__=='__main__':
Url="news.baidu/"
html=downloader(Url)
soup=bs4.BeautifulSoup(html,'html.parser')
伤心的情歌
alllist=soup.select('.bd')
exewriteinto(alllist,Url)
还是有⼩问题的 在学习中修正
也有⼩疑惑:soup.select中的div中class的名字 应该怎么去选择?

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。