在上面代码中加入反反爬虫技术
时间: 2023-12-06 08:43:34 浏览: 39
好的,反爬虫技术有很多种,我来介绍一些比较常用的方法:
1. 随机 User-Agent:将 User-Agent 设置为随机的值,可以避免被网站识别为爬虫。可以使用 fake_useragent 库生成随机的 User-Agent。
```python
import requests
from fake_useragent import UserAgent
url = 'http://www.example.com'
ua = UserAgent()
headers = {
'User-Agent': ua.random
}
response = requests.get(url, headers=headers)
```
2. 验证码识别:有些网站为了防止爬虫,会设置验证码。可以使用 pytesseract 库对验证码进行识别。
```python
import requests
from PIL import Image
import pytesseract
url = 'http://www.example.com/captcha.jpg'
response = requests.get(url)
with open('captcha.jpg', 'wb') as f:
f.write(response.content)
image = Image.open('captcha.jpg')
code = pytesseract.image_to_string(image)
```
3. IP 代理:使用代理 IP 可以隐藏真实 IP,避免被网站限制或封禁。可以使用代理池获取可用的代理 IP。
```python
import requests
url = 'http://www.example.com'
proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'http://127.0.0.1:8080',
}
response = requests.get(url, proxies=proxies)
```
4. 请求间隔:如果请求过于频繁,可能会被网站识别为爬虫。设置请求间隔可以避免这种情况。
```python
import requests
import time
url = 'http://www.example.com'
for i in range(10):
response = requests.get(url)
time.sleep(1)
```
以上是一些比较常用的反爬虫技术,可以根据具体情况选择合适的方法。