python网页爬取方法_Python之爬取其他网页

本文主要为大家分享一篇Python之爬取其他网页的请求方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧,希望能帮助到大家。

简单的说就是寻找网页中的超链接‘href’,之后将相对网址转变为绝对网址,在用for循环访问他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

相关推荐:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值