python爬取京东商品评论
时间: 2023-10-05 16:04:07 浏览: 34
好的,您可以使用 Python 中的 requests 和 BeautifulSoup 库来爬取京东商品评论。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://sclub.jd.com/comment/productPageComments.action?productId=100000177760&score=0&sortType=5&page=0&pageSize=10'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
comments = soup.select('div.comment-column J-comment-column > div.comment-con > div > div.comment-content > p')
for comment in comments:
print(comment.text.strip())
```
注意:需要替换 URL 中的 `productId` 参数为你想要爬取评论的商品 ID。另外,在爬取京东评论时需要注意反爬策略,建议添加适当的延迟和 User-Agent 头信息。
相关问题
写一个python爬取京东商品评论的脚本
好的,以下是一个简单的Python爬取京东商品评论的脚本,需要使用到requests、re、json、time、random等库:
```python
import requests
import re
import json
import time
import random
# 商品ID
product_id = '100003565439'
# 评论链接
comment_url = 'https://club.jd.com/comment/productPageComments.action?productId=' + product_id + '&score=0&sortType=5&page='
# 评论页数
max_page = 10
# 请求头
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'}
# 循环获取每一页评论
for page in range(1, max_page + 1):
# 随机延时一段时间
time.sleep(random.randint(1, 5))
# 构造请求链接
url = comment_url + str(page) + '&pageSize=10&isShadowSku=0&rid=0&fold=1'
# 发送请求
response = requests.get(url, headers=headers)
# 获取评论内容
comments = json.loads(re.findall('fetchJSON_comment98\((.*)\);', response.text)[0])['comments']
# 遍历评论列表,输出评论内容
for comment in comments:
print(comment['content'])
```
上述脚本会爬取指定商品ID的前10页评论内容,并输出到控制台中。你可以根据需要自行修改商品ID、评论页数等参数。请注意,爬取评论需要一定的时间和网络资源,建议合理使用。
python爬取京东商品信息
当然可以!以下是一个简单的示例代码,使用Python爬取京东商品信息:
```python
import requests
from bs4 import BeautifulSoup
def get_jd_product_info(url):
# 发送HTTP请求获取页面内容
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取商品信息
title = soup.find('div', class_='sku-name').text.strip()
price = soup.find('span', class_='p-price').find('span').text.strip()
comments = soup.find('a', id='comment-count').text.strip()
# 打印商品信息
print('商品名称:', title)
print('商品价格:', price)
print('商品评价:', comments)
# 要爬取的商品链接
url = 'https://item.jd.com/100008348542.html'
get_jd_product_info(url)
```
你只需要将`url`变量替换为你想要爬取的具体商品链接即可。这个代码使用了`requests`库发送HTTP请求获取页面内容,并使用`BeautifulSoup`库解析页面内容提取商品信息。然后,打印出商品的名称、价格和评价信息。
请注意,爬取网站信息时要遵守相关网站的使用条款,并尊重网站的隐私政策。