import requests
from lxml import etree
headers = {'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
}
def get_response(html_url):
response = requests.get(url=html_url,headers=headers)
return response
# https://www.beqege.com/1076/14341.html
def get_novel_url(html_url):
response = get_response(html_url)
response.encoding='utg-8'
tree = etree.HTML(response.text)
href_list = tree.xpath('//div[@id="list"]//dd//a//@href')
href = ['https://www.beqege.com'+i for i in href_list]
return href
def save(name,title,content):
with open(name+'.txt','a',encoding='utf-8') as f:
f.write(title)
f.write('\n')
f.write(content)
f.write('\n')
def get_novel_content(novel_url):
response = get_response(novel_url)
response.encoding = 'utg-8'(注意编码格式可能会有问题,用response.encoding=response.apparent_encoding改变编码)
tree = etree.HTML(response.text)
name_list = tree.xpath('//div[@class="con_top"]//a[3]//text()')
title_list = tree.xpath('//div[@class="bookname"]//text()')
content_list = tree.xpath('//div[@id="content"]//text()')
# 列表转化为字符串
name = name_list[0]
title = title_list[0]
content = ''.join(content_list)
save(name,title,content)
if __name__ == '__main__':
url = 'https://www.beqege.com/1076/'
href = get_novel_url(url)
for index in href:
get_novel_content(index)
注意:换一个headers,就可以了,但是爬久了,会被禁止访问,可以去买一个ip 试试看。亲测有效。
注意的事项:
需要加一句语句:response.encoding=response.apparent_encoding