Python之爬取其他网页

零到壹度
零到壹度 原创
2018-03-30 10:38:35 1809浏览

本文主要为大家分享一篇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

相关推荐:

Python爬取简单网页

python爬虫之爬取腾讯新闻

python爬取淘宝商品信息

以上就是Python之爬取其他网页的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。