python抓取动态网页(需安装的三方库示例代码示例说明:获取德邦官网)
优采云 发布时间: 2021-12-04 18:24python抓取动态网页(需安装的三方库示例代码示例说明:获取德邦官网)
前言
在抓取一个普通的静态网页时,我们可以直接请求相应的URL来获取完整的HTML页面,但是对于动态页面来说,网页显示的内容往往是通过ajax动态生成的,所以如果直接使用urllib.request的时候获取页面的HTML,就无法获取到我们想要的内容。然后我们就可以使用selenium库来获取我们需要的内容了。
需要安装的三方库示例代码
示例说明:获取德邦官网开设网点所在的城市区域名称
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless") #设置该参数使在获取网页时不打开浏览器
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path="./chromedriver")
driver.get("https://www.deppon.com/deptlist/")
html = driver.page_source
driver.close()
soup = BeautifulSoup(html, 'lxml')
items = soup.select('div[class~="listA_Z"] a')
for item in items:
print(item.string)
遇到的小问题用“pip install selenium”安装selenium库失败。您可以使用以下命令安装“pip install --trusted-host --trusted-host selenium”。使用webdriver.Chrome()时,出现问题。我在网上看到的文章用的是火狐浏览器。他们可以直接使用 webdriver.Firefox(),但我使用 Google Chrome。我以为使用谷歌浏览器和使用火狐是一样的,但是在运行时发生了错误。后来我在网上找到了。我想从 selenium 官网下载 Chrom Driver。然后,当使用 webdriver.chorme() 函数时,我需要上传它。executable_path参数,该参数的值为selenium官网下载的Chrome Driver.exe文件所在的路径。在示例中,我把chromedriver.exe放在根目录下,所以在代码中使用了相对路径(executable_path="./chromedriver")。推荐
Chrom/firefox浏览器插件:Katalon Recorder,Katalon Recorder是一个前端自动化测试插件,可以用来记录你在网页上的所有操作,最神奇的是它还可以导出记录到各种代码,其中收录 Python2 代码。有时候借用它,我们甚至可以不用分析HTML的结构就可以很容易的得到我们需要的数据,这对于HTML结构凌乱的网页非常有帮助。