采用cookies方式改写上面的程序
时间: 2024-04-17 17:27:36 浏览: 12
如果您希望使用 Cookies 的方式来进行爬取,您可以通过向请求头中添加 Cookies 来实现。以下是修改后的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,包括 User-Agent 和 Cookies
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
'Cookie': 'your_cookies_here'
}
# 请求页面
url = 'https://www.csdn.net/'
response = requests.get(url, headers=headers)
# 解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取文章列表
articles = soup.find_all('div', class_='title')
# 打印文章标题
for article in articles:
print(article.a.text.strip())
```
在上面的代码中,您需要将 `'your_cookies_here'` 替换为您自己的 Cookies。您可以在浏览器中登录 CSDN,然后使用开发者工具 (Developer Tools) 在请求头中找到包含 Cookies 的信息。
请注意,使用 Cookies 需要保护您的个人隐私和账户安全。请不要分享您的 Cookies 信息给他人,并定期更新您的 Cookies。
希望这对您有所帮助!如果您有任何其他问题,请随时提问。