# create a new Chrome browser instance browser = webdriver.Chrome() # navigate to the news website browser.get('https://www.bbc.com/news') # locate the top news articles articles = browser.find_elements_by_class_name('gs-c-promo-heading__title') # extract the titles of the top news articles for article in articles: print(article.text)
我们从网页中提取的数据通常是 HTML 或 XML 格式。为了理解这些数据,我们需要使用像 BeautifulSoup 这样的库来解析它。BeautifulSoup 是一个 Python 库,它允许我们从 HTML 和 XML 文件中提取数据。
这是我们如何使用 BeautifulSoup 从 HTML 文件中提取数据的示例:
from bs4 import BeautifulSoup
# define the HTML file html = '<html><body><h1>Hello, world!</h1></body></html>' # parse the HTML file soup = BeautifulSoup(html, 'html.parser') # extract the text from the <h1> tag text = soup.find('h1').get_text() # print the extracted text print(text)
在此示例中,我们将 HTML 文件定义为字符串并使用 BeautifulSoup 对其进行解析。然后我们使用该soup.find()方法定位标签并使用该get_text()方法提取其文本。
从动态网页中抓取数据
有时,网页使用在加载初始 HTML 后使用 JavaScript 加载的动态内容。这会使仅使用请求和 Beautiful Soup 来抓取数据变得困难。
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
url = 'https://www.amazon.com/gp/bestsellers/electronics/' driver = webdriver.Chrome() driver.get(url) wait = WebDriverWait(driver, 10) wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.zg_itemImmersion'))) items = driver.find_elements_by_css_selector('div.zg_itemImmersion') for item in items: title = item.find_element_by_css_selector('div.p13n-sc-truncated').text.strip() author = item.find_element_by_css_selector('a.a-size-small.a-link-child').text.strip() print(f"{title} by {author}")
driver.quit()
“网页抓取就像用剪刀剪草坪。当然,它有效,但结果很混乱,你错过了很多。” — 马克·伊顿
在这篇文章中,我们介绍了使用 Selenium 和 Python 进行网络抓取的基础知识。我们已经学习了如何从网页中提取数据、解析 HTML 和 XML 数据,甚至从动态加载的网页中抓取数据。