python爬虫爬取京东商品
时间: 2023-07-17 10:53:52 浏览: 122
好的,以下是一个简单的Python爬虫爬取京东商品的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://search.jd.com/Search?keyword=python&enc=utf-8&wq=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'}
response = requests.get(url, headers=headers)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
items = soup.select('#J_goodsList > ul > li > div > div.p-name > a')
for item in items:
print(item.text.strip())
```
这段代码会爬取搜索关键词为“python”的京东商品页面,并输出商品名称。你可以根据需要修改关键词和输出内容。
相关问题
python爬虫爬取京东商品价格
Python爬虫是一种可以自动化地从网页中获取信息的程序。要爬取京东商品价格,可以通过以下步骤实现:
1. 导入相关的库,例如requests、beautifulsoup4、re等。
2. 使用requests库发送网络请求,获取京东商品页面的HTML源码。
3. 使用beautifulsoup4库解析HTML源码,提取需要的商品信息。
4. 使用re库对提取的信息进行匹配和处理,提取商品价格。
5. 将价格输出或者存储到本地文件中。
以下是一个简单的示例代码,供参考:
```python
import requests
from bs4 import BeautifulSoup
import re
url = 'https://item.jd.com/100011843784.html'
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'}
# 发送网络请求,获取HTML源码
html = requests.get(url, headers=headers).text
# 解析HTML源码
soup = BeautifulSoup(html, 'html.parser')
# 提取商品价格
price = soup.find('span', {'class': 'price J-p-100011843784'}).text.strip()
price = re.sub(r'[^\d\.]', '', price) # 去除非数字和小数点的字符
print(price)
```
python爬虫爬取京东商品信息代码
Python爬虫用于从网站上抓取数据,京东的商品信息可以通过Scrapy框架或者requests库配合BeautifulSoup等库来实现。以下是一个基本的Python爬虫代码示例,使用了requests和BeautifulSoup来获取商品标题和价格:
```python
import requests
from bs4 import BeautifulSoup
# 定义京东商品URL
url = 'https://search.jd.com/Search?keyword=example_product&enc=utf-8&qrst=1'
def get_jd_item_info(url):
# 发送GET请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析HTML内容
soup = BeautifulSoup(response.text, 'lxml')
# 找到商品列表
item_list = soup.find_all('li', class_='gl-item')
for item in item_list:
# 提取商品标题和价格信息(这里只是一个示例,实际结构可能会有所不同)
title = item.find('div', class_='p-name').find('a').text
price = item.find('i', class_='price').text
print(f"商品标题: {title}, 价格: {price}")
else:
print(f"请求失败,状态码: {response.status_code}")
get_jd_item_info(url)
```