增加反爬机制的代码
时间: 2023-08-06 11:19:11 浏览: 47
好的,增加反爬机制的代码主要是为了模拟人类的浏览行为,防止被网站识别为爬虫并被封禁。以下是一个简单的示例,可以在遍历歌曲评论时加入等待时间和随机时间间隔,以模拟人类的浏览行为:
```python
import time
import random
for song in songs:
# 点击展开评论
show_comment_button = song.find_element_by_xpath('.//a[@class="s-fc9"]')
if '展开' in show_comment_button.text:
show_comment_button.click()
time.sleep(random.uniform(0.5, 1.5)) # 等待0.5~1.5秒
# 获取评论列表
comments = song.find_elements_by_xpath('.//div[@class="cntwrap"]/div[@class="cnt f-brk"]/span')
for comment in comments:
print(comment.text)
time.sleep(random.uniform(0.1, 0.5)) # 等待0.1~0.5秒
```
在上面的代码中,我们使用了`time.sleep()`函数来等待一段时间。`random.uniform()`函数用于生成一个随机的时间间隔,模拟人类的浏览行为。这样可以减缓访问速度,防止被网站识别为爬虫。