python爬虫商品代码
时间: 2024-06-03 11:05:51 浏览: 21
Python 爬虫的代码实现主要有以下几个步骤:
1. 导入需要的库和模块
2. 设置请求头
3. 发送请求获取网页源代码
4. 解析网页源代码获取需要的信息
5. 存储数据
以下是一个示例代码,可以用于爬取京东商城上的商品信息:
```
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'}
# 请求链接
url = 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=%E6%89%8B%E6%9C%BA&pvid=d1c2b7c2a4f04c8a894ef6d5d580bc9d'
# 发送请求获取网页源代码
response = requests.get(url, headers=headers)
# 解析网页源代码获取需要的信息
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.select('#J_goodsList .gl-item')
# 遍历商品信息并存储数据
for item in items:
name = item.select('.p-name em').get_text().strip()
price = item.select('.p-price strong i').get_text()
print(name, price)
```