python 20行代码爬取某网站小说全文
import requests
from bs4 import BeautifulSoup
import re
if __name__ == '__main__':
url = 'https://xxx.xxx.com/'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
main_rsp = requests.get(url=url, headers=headers)
main_rsp.encoding = 'utf-8'
soup = BeautifulSoup(main_rsp.text, 'lxml')
title_list = soup.select('.paiban > .menu-item > a')
fp = open('./三国演义.txt', 'w', encoding='utf-8')
for title_a in title_list:
title = title_a.text
rsp = requests.get(url=title_a['href'], headers=headers)
rsp.encoding = 'utf-8'
soup = BeautifulSoup(re.sub(' ', '', rsp.text), 'lxml')
content = soup.find('div', class_='grap').text
content = re.sub('\\n\\r\\n', '', content)
fp.write(title + '\n' + content + '\n')
print(f'章节->{title},爬取完成!!!')
fp.close()