我的目标是 : https://fanqienovel.com/page/7111874278269652002?enter_from=stack-room,爬取改网址的前10章内容。
下面是我的做法,但是好像有点错误,有人可以帮忙排错吗?
提供参考
你提供的爬取方式有点简单,需要进行一些改进。以下是一个示例代码,你可以参考一下:
import requests
from bs4 import BeautifulSoup
url = 'https://fanqienovel.com/page/7111874278269652002?enter_from=stack-room'
def get_chapter_content(chapter_url):
response = requests.get(chapter_url)
soup = BeautifulSoup(response.text, 'html.parser')
content = soup.find('div', class_='content')
text = content.text.replace('\n', '')
return text
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
chapter_links = soup.find_all('a', class_='chapter-link')[:10]
for link in chapter_links:
chapter_url = link['href']
chapter_title = link.text
chapter_content = get_chapter_content(chapter_url)
print(chapter_title)
print(chapter_content)
首先,我们定义了一个名为 get_chapter_content 的函数。该函数用于获取每个章节的内容。我们在其中发送一个GET请求,使用 BeautifulSoup 解析响应内容,然后返回章节正文的文本。
然后,我们使用 requests 库发送一个GET请求以获取页面内容,然后使用 Beautiful Soup 解析其内容。我们找到所有链接,然后使用 for 循环迭代前10个链接。对于每个链接,我们使用 get_chapter_content 函数获取正文,并将标题和内容打印出来。
请注意,这只是一个示例代码。根据你的实际需求,你可能需要进行一些更改来提高代码的健壮性和效率。同时,你需要了解是否存在网站防止爬虫的机制,以确保你的爬虫行为不会受到阻碍。