本文摘自php中文网,作者零到壹度,侵删。
本文主要为大家分享一篇Python之爬取其他网页的请求方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧,希望能帮助到大家。
简单的说就是寻找网页中的超链接‘href’,之后将相对网址转变为绝对网址,在用for循环访问他
1 2 3 4 5 6 7 8 9 10 11 12 | import requestsfrom bs4 import BeautifulSoup#将字符串转换为Python对象import pandas as pd
url = 'http://www.runoob.com/html/html-tutorial.html' r= requests.get(url)
html=r.text.encode(r.encoding).decode()
soup =BeautifulSoup(html, 'lxml' )#html放到beatifulsoup对象中l=[x.text for x in soup.findAll( 'h2' )]#提取次标题中所有的文字df = pd.DataFrame(l,columns =[url])#将l变为DataFrame文件,列名为URLx=soup.findAll( 'a' )[1]#查看第二个元素x.has_attr( 'href' )#判断是都有href字符x.attrs[ 'href' ]#获得超链接 attrs函数返回字典links = [i for i in soup.findAll( 'a' ) if i.has_attr( 'href' ) and i.attrs[ 'href' ][0:5]== '/html' ]#用 if 来做一个筛选relative_urls= set([i.attrs[ 'href' ] for i in links])
absolute_urls={ 'http://www.runoob.com' +i for i in relative_urls}
absolute_urls.discard(url)#删除当前所在的urlfor i in absolute_urls:
ri= requests.get(i)
soupi =BeautifulSoup(ri.text.encode(ri.encoding), 'lxml' )
li=[x.text for x in soupi.findAll( 'h2' )]
dfi = pd.DataFrame(l,columns =[i])
df = df.join(dfi,how= 'outer' )
df
|
相关推荐:
Python爬取简单网页
python爬虫之爬取腾讯新闻
python爬取淘宝商品信息
以上就是Python之爬取其他网页的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python怎么安装第三方库?
Python函数式编程是什么?
Python怎么统计不同字符的个数
Python学习笔记——os模块
介绍Python 数据抓取三种方法
Python3中时间处理与定时任务的方法介绍(附代码)
浅谈Python字符串
简述Python如何调用系统底层api播放wav文件
Python遍历文件夹下所有文件
Python迭代模式实例详解
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python之爬取其他网页