如何使用 Beautiful Soup 从公共网络中提取数据

beautiful soup 是一个用于从网页中抓取数据的 python 库。它创建用于解析 html 和 xml 文档的解析树,从而可以轻松提取所需的信息。
beautiful soup 为网页抓取提供了几个关键功能:
要使用 beautiful soup,您需要安装该库以及解析器,例如 lxml 或 html.parser。您可以使用 pip 安装它们
#install beautiful soup using pip. pip install beautifulsoup4 lxml
在处理跨多个页面显示内容的网站时,处理分页对于抓取所有数据至关重要。
import requests
from bs4 import beautifulsoup
base_url = 'https://example-blog.com/page/'
page_number = 1
all_titles = []
while true:
# construct the url for the current page
url = f'{base_url}{page_number}'
response = requests.get(url)
soup = beautifulsoup(response.content, 'html.parser')
# find all article titles on the current page
titles = soup.find_all('h2', class_='article-title')
if not titles:
break # exit the loop if no titles are found (end of pagination)
# extract and store the titles
for title in titles:
all_titles.append(title.get_text())
# move to the next page
page_number += 1
# print all collected titles
for title in all_titles:
print(title)
有时,您需要提取的数据嵌套在多层标签中。以下是如何处理嵌套数据提取。
import requests
from bs4 import beautifulsoup
url = 'https://example-blog.com/post/123'
response = requests.get(url)
soup = beautifulsoup(response.content, 'html.parser')
# find the comments section
comments_section = soup.find('div', class_='comments')
# extract individual comments
comments = comments_section.find_all('div', class_='comment')
for comment in comments:
# extract author and content from each comment
author = comment.find('span', class_='author').get_text()
content = comment.find('p', class_='content').get_text()
print(f'author: {author}\ncontent: {content}\n')
许多现代网站使用 ajax 动态加载数据。处理 ajax 需要不同的技术,例如使用浏览器开发人员工具监视网络请求并在抓取工具中复制这些请求。
import requests
from bs4 import BeautifulSoup
# URL to the API endpoint providing the AJAX data
ajax_url = 'https://example.com/api/data?page=1'
response = requests.get(ajax_url)
data = response.json()
# Extract and print data from the JSON response
for item in data['results']:
print(item['field1'], item['field2'])
网络抓取需要仔细考虑法律、技术和道德风险。通过实施适当的保护措施,您可以减轻这些风险并负责任且有效地进行网络抓取。
beautiful soup 是一个功能强大的库,它通过提供易于使用的界面来导航和搜索 html 和 xml 文档,从而简化了网页抓取的过程。它可以处理各种解析任务,使其成为任何想要从网络中提取数据的人的必备工具。
以上就是如何使用 Beautiful Soup 从公共网络中提取数据的详细内容,更多请关注php中文网其它相关文章!
《无所畏惧》温莉的结局是什么
时间:2023-11-25
《无所畏惧》刘铭的结局是什么
时间:2023-11-25
《无所畏惧》罗英子和陈硕最后在一起了吗
时间:2023-11-25
《宁安如梦》 姜雪宁是如何设计让薛姝去和亲
时间:2023-11-25
《宁安如梦》薛姝为了不和亲做了什么
时间:2023-11-25
《宁安如梦》为什么姜雪蕙只能当侧妃
时间:2023-11-25