python爬京东评论
时间: 2024-01-20 10:17:00 浏览: 18
以下是使用Python爬取京东商品评论的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_jd_comments(url):
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)
soup = BeautifulSoup(response.text, 'html.parser')
comments = soup.find_all('div', class_='comment-item')
for comment in comments:
content = comment.find('div', class_='comment-con').text.strip()
print(content)
print('--')
# 示例使用的京东商品链接
url = 'https://item.jd.com/100008348542.html#comment'
get_jd_comments(url)
```
这段代码使用了`requests`库发送HTTP请求,使用`BeautifulSoup`库解析HTML页面。首先,我们需要设置请求头部信息,以模拟浏览器访问。然后,发送GET请求获取页面内容,并使用`BeautifulSoup`解析页面。通过查找特定的HTML元素,我们可以提取出评论内容并打印出来。
请注意,示例中的链接是一个示例链接,你可以根据需要替换为你想要爬取评论的京东商品链接。