Python获取当前页面内所有链接的四种方法对比分析

yipeiwu_com7年前Python基础

本文实例讲述了Python获取当前页面内所有链接的四种方法。分享给大家供大家参考,具体如下:

'''
得到当前页面所有连接
'''
import requests
import re
from bs4 import BeautifulSoup
from lxml import etree
from selenium import webdriver
url = 'http://www.testweb.com'
r = requests.get(url)
r.encoding = 'gb2312'
# 利用 re (太黄太暴力!)
matchs = re.findall(r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')" , r.text)
for link in matchs:
  print(link)
print()
# 利用 BeautifulSoup4 (DOM树)
soup = BeautifulSoup(r.text,'lxml')
for a in soup.find_all('a'):
  link = a['href']
  print(link)
print()
# 利用 lxml.etree (XPath)
tree = etree.HTML(r.text)
for link in tree.xpath("//@href"):
  print(link)
print()
# 利用selenium(要开浏览器!)
driver = webdriver.Firefox()
driver.get(url)
for link in driver.find_elements_by_tag_name("a"):
  print(link.get_attribute("href"))
driver.close()

注意:若页面中含有 iframe,则 iframe 内所包含页面的所有标签都无法用以上四种方法获得!!!此时则要:

# 再打开所有iframe查找全部的a标签
for iframe in soup.find_all('iframe'):
  url_ifr = iframe['src'] # 取得当前iframe的src属性值 
  rr = requests.get(url_ifr)
  rr.encoding = 'gb2312'
  soup_ifr = BeautifulSoup(rr.text,'lxml')
  for a in soup_ifr.find_all('a'):
    link = a['href']
    m = re.match(r'http:\/\/.*?(?=\/)',link)
    #print(link)
    if m:
      all_urls.add(m.group(0))

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

100行python代码实现跳一跳辅助程序

100行python代码实现跳一跳辅助程序

写在前面 分享一下今天下午用python写的“跳一跳”小游戏的辅助程序。之前是准备用树莓派操控一个“机械手指”来代替人的触摸操作,但该方案还在酝酿中,实现了再分享。接下来要分享的是用“纯...

Python实现模拟时钟代码推荐

Python实现模拟时钟代码推荐 # coding=utf8 import sys, pygame, math, random from pygame.locals import *...

Python设计模式之观察者模式简单示例

Python设计模式之观察者模式简单示例

本文实例讲述了Python设计模式之观察者模式。分享给大家供大家参考,具体如下: 观察者模式是一个软件设计模式,一个主题对象包涵一系列依赖他的观察者,自动通知观察者的主题对象的改变,通常...

讲解Python中运算符使用时的优先级

讲解Python中运算符使用时的优先级

 运算符优先级来确定条件的表达式中的分组。这会影响一个表达式如何计算。某些运算符的优先级高于其他;例如,乘法运算符的优先级比加法运算更高。 例如x=7 + 3* 2;这里,x被...

python thread 并发且顺序运行示例

复制代码 代码如下:#-*- coding:utf-8 -*- import threading import time def fun(name, ls_name, front_thr...