Beautiful Soup 是一个 Python 库,可让您轻松地从 HTML 页面中提取数据。它可以使用各种解析器解析 HTML,例如内置的 Python 解析器、lxml 或 html5lib。 Beautiful Soup 可以帮助您通过标签、属性或文本内容找到特定元素。您还可以使用 .parent、.children 或 .next_sibling 等方法导航 HTML 树结构。 Beautiful Soup 对于网络抓取很有用,因为它可以获取 URL 的内容,然后解析它以提取您需要的信息。例如,您可以使用 Beautiful Soup 从亚马逊网站上抓取商品的标题、价格等信息。
首先安装所需的库:BeautifulSoup、requests和fake-useragent。
pip install beautifulsoup4 requests fake-useragent
下面是demo示例:
from bs4 import BeautifulSoup
import requests
from fake_useragent import UserAgent
# 定义爬取的亚马逊产品页面的URL
url = "https://www.amazon.com/dp/PRODUCT_ID"
# 设置随机UA
ua = UserAgent()
headers = {'User-Agent': ua.random}
# 动态转发隧道代理 使用代理IP提高采集成功率
# 亿牛云 爬虫代理加强版 服务器和用户名、密码认证
proxy_username = '16YUN'
proxy_password = '16IP'
proxy_host = 'www.16yun.cn'
proxy_port = '31000'
# 构造代理IP的格式
proxies = {
'http': f'http://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}',
'https': f'https://{proxy_username}:{proxy_password}@{proxy_host}:{proxy_port}'
}
# 发送请求并使用代理IP
response = requests.get(url, headers=headers, proxies=proxies)
soup = BeautifulSoup(response.content, 'html.parser')
# 提取产品信息
title_element = soup.find('span', id='productTitle')
price_element = soup.find('span', class_='price')
description_element = soup.find('div', id='productDescription')
title = title_element.text.strip()
price = price_element.text.strip()
description = description_element.text.strip()
# 打印产品信息
print("标题:", title)
print("价格:", price)
print("描述:", description)
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有