京东商城三页数据抓取python
时间: 2023-11-13 21:55:44 浏览: 100
您可以使用Python中的requests和BeautifulSoup库来实现京东商城三页数据的抓取。具体步骤如下:
1. 导入requests和BeautifulSoup库
```python
import requests
from bs4 import BeautifulSoup
```
2. 构造请求头和请求参数
```python
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'}
params = {
'keyword': '手机',
'enc': 'utf-8',
'page': 1
}
```
3. 发送请求并解析响应
```python
url = 'https://search.jd.com/Search'
response = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
```
4. 提取数据
```python
items = soup.select('#J_goodsList .gl-item')
for item in items:
name = item.select('.p-name em')[0].text.strip()
price = item.select('.p-price i')[0].text.strip()
print(name, price)
```
5. 循环抓取多页数据
```python
for page in range(1, 4):
params['page'] = page
response = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.select('#J_goodsList .gl-item')
for item in items:
name = item.select('.p-name em')[0].text.strip()
price = item.select('.p-price i')[0].text.strip()
print(name, price)
```
阅读全文