python 爬虫爬取亚马逊
时间: 2023-09-24 11:07:47 浏览: 58
您可以使用Python编写爬虫来爬取亚马逊的商品信息。以下是一个简单的示例代码,使用BeautifulSoup和Requests库来实现:
```python
import requests
from bs4 import BeautifulSoup
def get_amazon_products(keyword):
url = f"https://www.amazon.com/s?k={keyword}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
products = soup.find_all("div", class_="sg-col-inner")
for product in products:
title = product.find("span", class_="a-size-medium a-color-base a-text-normal").text.strip()
price = product.find("span", class_="a-offscreen").text.strip()
print(f"Title: {title}")
print(f"Price: {price}")
print("==========================")
keyword = input("请输入要搜索的关键词:")
get_amazon_products(keyword)
```
这个代码使用了requests发送HTTP请求,并设置了一个伪装的User-Agent头部,以模拟浏览器访问。然后使用BeautifulSoup解析HTML页面,提取出商品的标题和价格,并进行打印输出。
请注意,爬取亚马逊是需要注意法律和道德问题的,确保您的爬虫行为符合相关规定。此外,网站可能会对爬虫进行反爬虫的限制,需要注意处理相应的反爬虫手段。