Web 抓取:Selenium 与 BeautifulSoup 的对比。
我们可以使用 Selenium Webdriver 和 BeautifulSoup 来执行 web 抓取。Web 抓取用于从页面中提取内容。在 Python 中,这是通过 BeautifulSoup 包实现的。
我们抓取并获取页面上的以下链接 −

我们还将看到上述链接的 html 结构 −

我们来看看如何使用 BeautifulSoup 进行 web 抓取
要安装 Beautifulsoup 所需的包,我们应该运行以下命令 −
pip install bs4 pip install requests

示例
from bs4 import BeautifulSoup
import requests
#get all response
d=requests.get("https://tutorialspoint.com/about/about_careers.htm")
#response content whole page in html format
s = BeautifulSoup(d.content, 'html.parser')
#access to specific ul element with BeautifulSoup methods
l = s.find('ul', {'class':'toc reading'})
#access all children of ul
rs = l.findAll('li')
for r in rs:
#get text of li elements
print(r.text)现在,我们来看看如何将 BeautifulSoup 与 Selenium 一起用于 web 抓取。
要将 BeautifulSoup 与 Selenium 一起使用,我们应该运行命令 −
pip install bs4 selenium

示例
from selenium import webdriver
from bs4 import BeautifulSoup
#path of chromedriver.exe
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
#launch browser
driver.get ("https://tutorialspoint.com/about/about_careers.htm")
#content whole page in html format
s = BeautifulSoup(driver.page_source, 'html.parser')
#access to specific ul element with BeautifulSoup methods
l = s.find('ul', {'class':'toc reading'})
#get all li elements under ul
rs = l.findAll('li')
for r in rs:
#get text of li elements
print(r.text)输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP