import requests
import json
# 设置代理信息
proxy_host = 'https://www.duoip.cn/get_proxy'
proxy_port = 8000
# 爬虫网址
url = 'https://www.douyin.com/video/6725697353081346886/comments'
# 使用 requests 库发送 GET 请求
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, proxies={'http': f'http://{proxy_host}:{proxy_port}'})
response.encoding = 'utf-8'
# 解析 JSON 数据
comments = json.loads(response.text)
# 打印评论内容
for comment in comments['comments']:
print(comment['text'])
代码解释:
- 导入
requests
库和json
库,用于发送和解析 HTTP 请求。 - 设置代理信息,包括主机名和端口号。
- 设置要爬取的网址。
- 使用
requests.get
函数发送 GET 请求,设置User-Agent
头部信息和代理信息。 - 获取响应体,并设置编码为 UTF-8。
- 使用
json.loads
函数将响应体解析为 JSON 格式。 - 遍历 JSON 数据中的每一个评论,打印其内容。
注意:这只是一个简单的爬虫程序,实际使用时需要处理更多的异常情况和错误。同时,爬虫行为可能会被目标网站检测到并封禁,使用前请确保遵守相关法律法规和网站使用协议。