模拟登录“古诗文网”:用自己的用户名和密码登录后,爬取个人收藏列表的古诗的名字和作者
时间: 2024-02-18 13:04:58 浏览: 29
好的,这个问题可以通过模拟登录古诗文网,并爬取个人收藏列表来解决。以下是实现的步骤:
1. 导入必要的库:requests、BeautifulSoup、re、json、time、selenium
2. 使用selenium模拟登录古诗文网,获取登录后的cookies
3. 使用requests库发送请求,带上cookies获取个人收藏列表页面的HTML内容
4. 使用BeautifulSoup解析HTML内容,获取收藏列表中每首古诗的链接
5. 使用requests库发送请求,获取每首古诗的具体页面HTML内容
6. 使用正则表达式或BeautifulSoup解析HTML内容,获取古诗的名字和作者
以下是代码实现的详细步骤:
```python
import requests
from bs4 import BeautifulSoup
import re
import json
import time
from selenium import webdriver
# 设置登录账号和密码
username = "your_username"
password = "your_password"
# 使用selenium模拟登录获取cookies
login_url = "https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx"
driver = webdriver.Chrome()
driver.get(login_url)
driver.find_element_by_id("email").send_keys(username)
driver.find_element_by_id("pwd").send_keys(password)
driver.find_element_by_id("denglu").click()
time.sleep(5)
cookies = driver.get_cookies()
cookies_dict = {}
for cookie in cookies:
cookies_dict[cookie['name']] = cookie['value']
# 使用cookies发送请求获取收藏列表页面的HTML内容
collection_url = "https://so.gushiwen.cn/user/collect.aspx"
response = requests.get(collection_url, cookies=cookies_dict)
html = response.text
# 使用BeautifulSoup解析HTML内容,获取收藏列表中每首古诗的链接
soup = BeautifulSoup(html, "html.parser")
poems = soup.find_all("div", class_="sons")
poem_links = []
for poem in poems:
link = poem.find("a")["href"]
poem_links.append("https://so.gushiwen.cn" + link)
# 使用requests库发送请求,获取每首古诗的具体页面HTML内容,并使用正则表达式或BeautifulSoup解析HTML内容,获取古诗的名字和作者
for link in poem_links:
response = requests.get(link, cookies=cookies_dict)
html = response.text
soup = BeautifulSoup(html, "html.parser")
title = soup.find("div", class_="cont").find("h1").text.strip()
author = soup.find("div", class_="cont").find("p", class_="source").text.strip()
author = re.sub(r"\s+", " ", author).split(" ")[0][:-1]
print(title, author)
```
这样就可以成功爬取个人收藏列表中的古诗的名字和作者了。