python怎么获取动态网页链接?

Python07

python怎么获取动态网页链接?,第1张

四中方法:

'''

得到当前页面所有连接

'''

import requests

import re

from bs4 import BeautifulSoup

from lxml import etree

from selenium import webdriver

url = 'http://www.ok226.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()

爬虫流程

其实把网络爬虫抽象开来看,它无外乎包含如下几个步骤

模拟请求网页。模拟浏览器,打开目标网站。

获取数据。打开网站之后,就可以自动化的获取我们所需要的网站数据。

保存数据。拿到数据之后,需要持久化到本地文件或者数据库等存储设备中。

那么我们该如何使用 Python 来编写自己的爬虫程序呢,在这里我要重点介绍一个 Python 库:Requests。

Requests 使用

Requests 库是 Python 中发起 HTTP 请求的库,使用非常方便简单。

模拟发送 HTTP 请求

发送 GET 请求

当我们用浏览器打开豆瓣首页时,其实发送的最原始的请求就是 GET 请求

import requests

res = requests.get('http://www.douban.com')

print(res)

print(type(res))

>>>

<Response [200]>

<class 'requests.models.Response'>