用python写一个爬取京东商品代码
时间: 2024-01-02 18:03:12 浏览: 39
以下是一个简单的爬取京东商品信息的python代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 输入需要搜索的商品名称
search_name = input('请输入要搜索的商品名称:')
# 将商品名称进行url编码
url_name = requests.utils.quote(search_name)
# 构造请求链接
url = 'https://search.jd.com/Search?keyword=' + url_name + '&enc=utf-8'
# 发送请求
response = requests.get(url, headers=headers)
# 解析响应
soup = BeautifulSoup(response.text, 'html.parser')
# 获取搜索结果列表
product_list = soup.select('.gl-item')
# 遍历列表,提取商品信息
for product in product_list:
# 商品名称
title = product.select('.p-name em')[0].text.strip()
# 商品价格
price = product.select('.p-price i')[0].text.strip()
# 商品链接
link = 'https:' + product.select('.p-name a')[0]['href']
# 商品图片链接
img_link = product.select('.p-img img')[0]['src']
# 打印商品信息
print('商品名称:', title)
print('商品价格:', price)
print('商品链接:', link)
print('商品图片链接:', img_link)
print('-------------------------------------')
```
使用方法:
1. 将以上代码保存为一个`jd_spider.py`文件。
2. 在终端中进入该文件所在的目录。
3. 运行命令`python jd_spider.py`。
4. 输入需要搜索的商品名称并回车,即可开始爬取。