Python网络爬虫笔记(3)移至其他网页爬取

本文介绍了一种使用Python爬取指定网页上所有超链接的方法,并将其转化为绝对路径进行访问。通过BeautifulSoup解析HTML,提取出所有带有'href'属性的链接,并利用pandas整理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

import requests
from 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文件,列名为URL
x=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)#删除当前所在的url
for 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值